﻿using System;
using System.Collections.Generic;
using System.ComponentModel;

using System.ComponentModel.Design;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Data.Objects;
using System.Data.Objects.DataClasses;
using System.Windows.Forms;
using System.Drawing.Design;
using System.Reflection;
using DevExpress.XtraSplashScreen;
//using System.Reflection.Emit;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraBars;
using Fcdbas.Platform.Interface;
using Fcdbas.WinUI.Common;
using Fcdbas.Core.Windows;
using Fcdbas.WinUI.Design;
using Fcdbas.WinUI.Windows;
using Fcdbas.Platform.Properties;
using Fcdbas.Platform;
using Fcdbas.WinUI.Controls;
using Fcdbas.Platform.Enums;
using Fcdbas.Core;
using Fcdbas.Biz;
using Fcdbas.Core.Xml;

namespace Fcdbas.WinUI.Forms
{
   
    public partial class BaseForm : XtraForm,ISalWindow, ISalForm, IView
    {
        public ISalWindow _derived;
        protected SalWindow m_salWindow;
        private int m_returnValue;
        private SalFormState m_state;
        private System.Windows.Forms.Form m_savedOwner;
        private static bool? _UIDebug ;
        public static bool UIDebug
        {
            get
            {
                if (_UIDebug != null)
                    return _UIDebug.Value;
                else
                {
                    _UIDebug = Fcdbas.Core.Configuration.Config.GetMutilConfig<bool>(false, "UI.Debug");
                    return _UIDebug.Value;
                }
            }
        }
        protected WindowProfile WinProfile;
        /// <summary>
        /// 调用打开新建功能，不需要刷新子表
        /// </summary>
       // protected bool IsCreateWithNew = false;
       // protected List<UserQueryProfile> QueryProfiles = new List<UserQueryProfile> ();
        public bool UseProfile = true;
        /// <summary>
        /// 选取LOV值后发生
        /// </summary>
        [Category("F1 Late Bind Events"), Description("选取LOV值后发生."), DisplayName("DataItemLovDone")]
        public event EventHandler<DataItemLovEventArgs> DataItemLovDone;
        /// <summary>
        /// 查询LOV值的条件，可以干预查询条件
        /// </summary>
        [Category("F1 Late Bind Events"), Description("查询LOV值的条件，可以干预查询条件."), DisplayName("DataItemLovUserWhere")]
        public event EventHandler<cDataSource.ReturnEventArgsSalString> DataItemLovUserWhere;
        /// <summary>
        /// 查询LOV值的排序方式，可以干预查询排序
        /// </summary>
        [Category("F1 Late Bind Events"), Description("查询LOV值的排序方式，可以干预查询排序."), DisplayName("DataItemLovOrderBy")]
        public event EventHandler<cDataSource.ReturnEventArgsSalString> DataItemLovOrderBy;
        /// <summary>
        /// 可以干预是否启用LOV
        /// </summary>
        [Category("F1 Late Bind Events"), Description("可以干预是否启用LOV."), DisplayName("DataItemLovInquire")]
        public event EventHandler<cDataSource.ReturnEventArgsSalBoolean> DataItemLovInquire;
        /// <summary>
        /// 可以干预LOV是否开启多选
        /// </summary>
       [Category("F1 Late Bind Events"), Description("可以干预LOV是否开启多选."), DisplayName("LovQueryMultipleSelectioin")]
        public event EventHandler<cDataSource.ReturnEventArgsSalBoolean> LovQueryMultipleSelectioin;
        [Category("F1 Late Bind Events"), Description("可以干预Zoom."), DisplayName("DataItemZoomInquire")]
        public event EventHandler<cDataSource.ReturnEventArgsSalBoolean> DataItemZoomInquire;
        /// <summary>
        /// 数据保存完成触发
        /// </summary>
       [Category("F1 Late Bind Events"), Description("数据保存完成触发,Return=true表示成功，false表示失败."), DisplayName("DataSourceSaveCompleted")]
        public event EventHandler<cDataSource.ReturnEventArgsSalBoolean> DataSourceSaveCompleted;
        public void OnDataItemLovDone(object sender, string val)
        {
            if (DataItemLovDone != null)
                DataItemLovDone.Invoke(sender, new DataItemLovEventArgs(val));
        }
        public SalString OnDataItemLovUserWhere(object sender)
        {
            if (DataItemLovUserWhere != null)
            {
                cDataSource.ReturnEventArgsSalString ret = new cDataSource.ReturnEventArgsSalString();
                ret.ReturnValue = "";
                DataItemLovUserWhere.Invoke(sender, ret);
                //if (ret.Handled)
                    return ret.ReturnValue;
            }
            return "";
        }
        public SalBoolean OnDataItemLovInquire(object sender)
        {
            if (DataItemLovInquire != null)
            {
                cDataSource.ReturnEventArgsSalBoolean ret = new cDataSource.ReturnEventArgsSalBoolean();
                DataItemLovInquire.Invoke(sender, ret);
                //if (ret.Handled)
                    return ret.ReturnValue;
            }
            return true;
        }
        public SalBoolean OnLovQueryMultipleSelectioin(object sender)
        {
            if (LovQueryMultipleSelectioin != null)
            {
                cDataSource.ReturnEventArgsSalBoolean ret = new cDataSource.ReturnEventArgsSalBoolean();
                LovQueryMultipleSelectioin.Invoke(sender, ret);
                //if (ret.Handled)
                    return ret.ReturnValue;
            }
            return true;
        }
       
        public SalString OnDataItemLovOrderBy(object sender)
        {
            if (DataItemLovOrderBy != null)
            {
                cDataSource.ReturnEventArgsSalString ret = new cDataSource.ReturnEventArgsSalString();
                ret.ReturnValue = "";
                DataItemLovOrderBy.Invoke(sender, ret);
                //if (ret.Handled)
                    return ret.ReturnValue;
            }
            return "";
        }
        public SalBoolean OnDataItemZoomInquire(object sender)
        {
            if(DataItemZoomInquire != null)
            {
                cDataSource.ReturnEventArgsSalBoolean ret = new cDataSource.ReturnEventArgsSalBoolean();
                DataItemZoomInquire.Invoke(sender, ret);
                //if (ret.Handled)
                return ret.ReturnValue;
            }
            return true;
        }
        public List<fnd_user_profile> UQProfile
        {
            get
            {
                if (currentSourceBinding != null)
                    return currentSourceBinding.QueryProfile;
                else
                    return null;
            }
        }
        private System.Collections.Generic.List<System.Collections.Generic.KeyValuePair<System.Windows.Forms.Keys, cButton>> m_acceleratorTable;
        public BaseForm()
        {
            m_salWindow = new SalWindow(this);
            WindowActions += new WindowActionsEventHandler(BaseForm_WindowActions);
            InitializeComponent();
            
            m_salWindow.AddWindowActions(this.MasterdataSourceBinding);
            translate = new WinTranslate("Fcdbas", "Fcdbas", "C", "");
            //baseLinks = new List<BarItem>();
            //for (int i = 0; i < this.BaseMenu.LinksPersistInfo.Count; i++)
            //{
            //    baseLinks.Add(this.BaseMenu.LinksPersistInfo[i].Item);
            //    if (this.BaseMenu.LinksPersistInfo[i].BeginGroup)
            //        menuBeginGroups.Add(this.BaseMenu.LinksPersistInfo[i].Item);
            //}
        }
       // public List<DataItem> VisibleDataItems = new List<DataItem>();
       // private List<BarItem> baseLinks;
       // private List<BarItem> menuBeginGroups = new List<BarItem>();
        public List<Control> ControlList = new List<Control>();
        public BaseForm(bool isNew)
        {
            m_salWindow = new SalWindow(this);
            WindowActions += new WindowActionsEventHandler(BaseForm_WindowActions);
            InitializeComponent();
           
            m_salWindow.AddWindowActions(this.MasterdataSourceBinding);
           
        }
        public frmMainForm MainForm
        {
            get;
            set;
        }
        private bool _sysSave = true;
        /// <summary>
        /// 是否由框架判断是否需要保存
        /// </summary>
        [Description("是否由框架判断是否需要保存")]
        public bool IsSysSave
        {
            get { return _sysSave; }
            set { _sysSave = value; }
        }
        protected DataSourceBinding currentSourceBinding;
        public DataSourceBinding CurrentSourceBinding
        {
            get
            {
                if (currentSourceBinding != null)
                    return currentSourceBinding;
                else
                    return MasterdataSourceBinding;
            }
        }
        public DialogResult Warning(SalString sMsg)
        {
            DialogResult result;

            result = this.ShowMessage(sMsg, "", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1);
            return result;
        }

        public DialogResult Question(SalString sMsg)
        {
            DialogResult result;

            result =ShowMessage(sMsg, "", System.Windows.Forms.MessageBoxButtons.YesNoCancel, System.Windows.Forms.MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
            return result;
        }

        public DialogResult Information(SalString sMsg)
        {
            DialogResult result;

            result = ShowMessage(sMsg, "", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
            return result;
        }

        public DialogResult Error(SalString sMsg)
        {
            DialogResult result;

            result = ShowMessage(sMsg, "", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
            return result;
        }
        public DialogResult ShowMessage(string msgCode)
        {
            return this.translate.ShowMessage(msgCode);
        }
        /// <summary>
        /// 显示对话框。
        /// </summary>
        /// <param name="msgCode">消息代码</param>
        /// <param name="msgAdd">消息参数，多个参数之间用","分开</param>
        /// <returns>选择结果</returns>
        public DialogResult ShowMessage(string msgCode, string msgAdd)
        {
            return translate.ShowMessage(msgCode, msgAdd);
        }

        public DialogResult ShowMessage(string msgCode, string msgAdd, MessageBoxButtons btnType)
        {
            return translate.ShowMessage(msgCode, msgAdd, btnType);
        }
        public DialogResult ShowMessage(string msgCode, string msgAdd, MessageBoxButtons btnType, MessageBoxIcon iconType)
        {
            return translate.ShowMessage(msgCode, msgAdd, btnType, iconType);
        }
        public DialogResult ShowMessage(string msgCode, string msgAdd, MessageBoxButtons btnType, MessageBoxIcon iconType, MessageBoxDefaultButton defaultType)
        {
            return translate.ShowMessage(this, msgCode, msgAdd, btnType, iconType, defaultType);
        }
        public DialogResult ShowMessage(IWin32Window owner, string msgCode, string msgAdd, MessageBoxButtons buttonsType, MessageBoxIcon iconType, MessageBoxDefaultButton defaultButton)
        {
            return translate.ShowMessage(owner, msgCode, msgAdd, buttonsType, iconType, defaultButton);
        }
        public WinTranslate translate;
        /// <summary>
        /// 导航信息
        /// </summary>
        [Browsable(false)]
        public string NavMsg
        {
            get;
            set;
        }
        public string FormName
        {
            get { return this.Name; }
        }
        private bool _isCreateByOth = false;
        /// <summary>
        /// 表示是通过SalCreateWindow打开的，自动抽取数据
        /// </summary>
        [Browsable(false)]
        public bool IsCreateByOth
        {
            get
            {
                return _isCreateByOth;
            }
            set
            {
                _isCreateByOth = value;
            }
        }
        private bool _isAutoPopulate = true;
        /// <summary>
        /// 是否自动抽取Detail数据
        /// </summary>
        [Description("是否自动抽取Detail数据")]
        [Category("Fcdbas")]
        [DefaultValue(true)]
        public bool IsAutoPopulate
        {
            get
            {
                return _isAutoPopulate;
            }
            set
            {
                _isAutoPopulate = value;
            }
        }
        public WinUtil winUtil;
        private void BaseForm_Load(object sender, EventArgs e)
        {
            MasterdataSourceBinding.ParentForm = this;
            
            AttachToForm(this.ChildContainer);
            if (!DesignMode)
            {
                currentSourceBinding = this.MasterdataSourceBinding;
                //translate = new WinTranslate(System.Diagnostics.Process.GetCurrentProcess().ProcessName, "Fcdbas", "C", "");
                
               
                //translate.TranslateForm(this.Name, this);
                //SplashScreenManager.ShowForm(this, typeof(SaveSplashScreen), true, true, false);
                Fcdbas.Core.Log.XTrace.WriteLine("TEST:开始加载网格配置！！！！");
                winUtil = new WinUtil(this);
                winUtil.LoadGridLayouts(this);
              //  this.Font = new Font(AppEnvironment.AppOption.FontName, AppEnvironment.AppOption.FontSize);
                winUtil.CreateGridPopupMenuToForm(this);
                DicMenu.Add(misTemplate.Name, misTemplate);
                Fcdbas.Core.Log.XTrace.WriteLine("TEST:开始加载Window配置！！！！");
                LoadWindowProfile();
                Fcdbas.Core.Log.XTrace.WriteLine("TEST:开始加载用户查询配置！！！！");
                LoadUserQueryfile();
                Fcdbas.Core.Log.XTrace.WriteLine("TEST:开始加载模板配置！！！！");
                LoadUserTemplatefile();
                AddUserTemplateMenu();
                MasterdataSourceBinding.InitDataSource();
                MasterdataSourceBinding.FetchRowsDone += new EventHandler<cDataSource.ReturnEventArgsSalNumber>(MasterdataSourceBinding_FetchRowsDone);
                Fcdbas.Core.Log.XTrace.WriteLine("TEST:初始化控件！！！！");
                InitControls(this);
                Fcdbas.Core.Log.XTrace.WriteLine("TEST:初始化数据源和加载数据！！！！");
                InitBind();
                ClearGridEmptyRow();
               
                MasterdataSourceBinding.CurrentChanged += new EventHandler(MasterdataSourceBinding_CurrentChanged);
                MasterdataSourceBinding.Session.DataSourceSaveCompleted += new EventHandler(this.Session_DataSourceSaveCompleted);
                MasterdataSourceBinding.Session.DataSourceDeleted += new cDataSource.DataRecordDeletedEventHandler(Session_DataSourceDeleted);
                
                fnd_pres_object preObj = FndDAL.FindPresObject(this.GetType().FullName);
                if (preObj == null)
                {
                    preObj = FndObjectFactory.CreatePreObject(this.GetType(), this.MasterdataSourceBinding.LogicalUnit, this.MasterdataSourceBinding.Module, this.Text);
                    FndDAL.PresObjectNew(preObj,true);
                }
                Fcdbas.Core.Log.XTrace.WriteLine("TEST:权限配置！！！！");
                AddFunctionItem();
                LoadMenuAvaliable(); 
                SetMainFunction();
                AdjustMenu();
                if(MainForm != null)
                    MainForm.SetNewRecordEnable();
                SetMenuEnable();
                Fcdbas.Core.Log.XTrace.WriteLine("TEST:BaseForm加载完成！！！！");
            }
        }
        private int DtlCount = 0;
        private bool MasterDone = false;
        protected void MasterdataSourceBinding_FetchRowsDone(object sender, cDataSource.ReturnEventArgsSalNumber e)
        {
            if (!IsAutoPopulate)
            {
                SplashScreenManager.CloseForm(false);
            }
            else
            {
                if (!currentSourceBinding.Equals(this.MasterdataSourceBinding))
                {
                    SplashScreenManager.CloseForm(false);
                }
                else
                {
                    if (currentSourceBinding.Details == null || currentSourceBinding.Details.Count == 0)
                    {
                        SplashScreenManager.CloseForm(false);
                    }
                    else
                    {
                        DataSourceBinding dsb= sender as DataSourceBinding;
                        if (this.MasterdataSourceBinding.Equals(dsb))
                        {
                            MasterDone = true;
                            if (this.MasterdataSourceBinding.List == null || this.MasterdataSourceBinding.List.Count == 0)
                                SplashScreenManager.CloseForm(false);
                            else
                            {
                                IEntity en = this.MasterdataSourceBinding.Current as IEntity;
                                if(en != null && en["objid"] == null)
                                    SplashScreenManager.CloseForm(false);
                            }
                        }
                        else
                            DtlCount++;
                        if(MasterDone && DtlCount == currentSourceBinding.Details.Count )
                            SplashScreenManager.CloseForm(false);

                    }
                }
            }

        }
        private void SetMergeMenuEnable(string name,bool enable)
        {
            if (DicBaseMenu.ContainsKey(name))
            {
                List<ToolStripItem> list = DicBaseMenu[name];
                for (int i = 0; i < list.Count; i++)
                    list[i].Enabled = enable;
            }
        }
        /// <summary>
        /// 控制菜单
        /// </summary>
        protected virtual void SetMenuEnable()
        {
            //if (!CurrentSourceBinding.AllowNew || CurrentSourceBinding.Updates == Platform.Enums.UpdatesSql.ReadOnly)
            //    miCopy.Enabled = miDelete.Enabled = miPasteObject.Enabled = miNew.Enabled = false;
            //else
            //    miCopy.Enabled = miDelete.Enabled = miPasteObject.Enabled = miNew.Enabled = IsDataSourceNew();

            if (CurrentSourceBinding != null)
            {
                if (!CurrentSourceBinding.AllowNew || CurrentSourceBinding.Updates == Platform.Enums.UpdatesSql.ReadOnly)
                {
                    miCopy.Enabled = miNew.Enabled = false;
                    SetMergeMenuEnable(miCopy.Name, false);
                    SetMergeMenuEnable(miNew.Name, false);
                }
                else
                {

                    miCopy.Enabled = miNew.Enabled = IsDataSourceNew();
                    SetMergeMenuEnable(miCopy.Name, IsDataSourceNew());
                    SetMergeMenuEnable(miNew.Name, IsDataSourceNew());
                    if (CurrentSourceBinding.DataSource is IEntity || CurrentSourceBinding.DataSource == null)
                    {
                        miCopy.Enabled = miDelete.Enabled = false;
                        SetMergeMenuEnable(miCopy.Name, false);
                        SetMergeMenuEnable(miDelete.Name, false);
                    }

                }
                if (!CurrentSourceBinding.AllowRemove || CurrentSourceBinding.Updates == Platform.Enums.UpdatesSql.ReadOnly || CurrentSourceBinding.DataSource is IEntity)
                {
                    miDelete.Enabled = false;
                    SetMergeMenuEnable(miDelete.Name, false);
                }
                else
                {
                    miDelete.Enabled = IsDataSourceDelete();
                    SetMergeMenuEnable(miDelete.Name, IsDataSourceDelete());
                }
            }
            SetMenuEnableWithParent();
        }
        protected virtual void SetMenuEnableWithParent()
        {
            if (CurrentSourceBinding == null || CurrentSourceBinding.LogicalParent == null || CurrentSourceBinding.LogicalParent.Current == null)
                return;
            IEntity cn = CurrentSourceBinding.LogicalParent.Current as IEntity;
            if (cn.Status != RecordStatus.Normal || CurrentSourceBinding.LogicalParent.DataSource is IEntity)
            {
                miCopy.Enabled = miNew.Enabled = miDelete.Enabled = false;
                SetMergeMenuEnable(miCopy.Name, false);
                SetMergeMenuEnable(miDelete.Name, false);
                SetMergeMenuEnable(miNew.Name, false);
               
            }
        }
        private List<fnd_user_profile> QProfiles;
        protected void LoadUserQueryfile()
        {
            QProfiles = FndDAL.FindUserProfiles(AppEnvironment.Session.USER_ID, this.GetType().FullName, "Q");
            if (QProfiles != null)
            {
               // QueryProfiles = new List<UserQueryProfile>();
                var ds = from c in QProfiles
                         where c.data_source == MasterdataSourceBinding.Name
                         select c;
                if (ds != null)
                {

                    MasterdataSourceBinding.QueryProfile = ds.ToList();
                }
                if (ChildContainer != null)
                {
                    for (int i = 0; i < ChildContainer.Components.Count; i++)
                    {
                        if (ChildContainer.Components[i] is DataSourceBinding)
                        {
                            DataSourceBinding dataSourceBinding = ChildContainer.Components[i] as DataSourceBinding;
                            if (string.IsNullOrEmpty(dataSourceBinding.PackageName))
                                continue;
                            var ds1 = from c in QProfiles
                                      where c.data_source == dataSourceBinding.Name
                                      select c;
                            // UserQueryProfile uq = QueryProfiles.Find(p => p.DataSourceName == dataSourceBinding.Name);
                            dataSourceBinding.QueryProfile = ds1.ToList();
                        }
                    }
                }
            }
            else
            {
               
                MasterdataSourceBinding.QueryProfile = new List<fnd_user_profile> ();
               
                if (ChildContainer != null)
                {
                    for (int i = 0; i < ChildContainer.Components.Count; i++)
                    {
                        if (ChildContainer.Components[i] is DataSourceBinding)
                        {
                            DataSourceBinding dataSourceBinding = ChildContainer.Components[i] as DataSourceBinding;
                            
                            dataSourceBinding.QueryProfile = new List<fnd_user_profile> ();
                           
                        }
                    }
                }
                //QueryProfile.QueryItems = new List<UserQueryItem>();
                //QueryProfile.PreObject = this.GetType().FullName;
            }
        }
        public void SaveUserQueryfile(fnd_user_profile QProfile,bool IsOnlyLocal=false)
        {
           // QProfile.info = QueryProfiles.ToXml();
            if (QProfile.Status == RecordStatus.New)
            {
                FndDAL.UserProfileNew(QProfile,IsOnlyLocal);
            }
            else
            {
                FndDAL.UserProfileModify(QProfile,IsOnlyLocal);
            }
        }

        private List<fnd_user_profile> UTemplates;
        protected void LoadUserTemplatefile()
        {
            UTemplates = FndDAL.FindUserProfiles(AppEnvironment.Session.USER_ID, this.GetType().FullName, "T");
            if (UTemplates != null)
            {
                // QueryProfiles = new List<UserQueryProfile>();
                var ds = from c in UTemplates
                         where c.data_source == MasterdataSourceBinding.Name
                         select c;
                if (ds != null)
                {

                    MasterdataSourceBinding.UserTemplates = ds.ToList();
                }
                if (ChildContainer != null)
                {
                    for (int i = 0; i < ChildContainer.Components.Count; i++)
                    {
                        if (ChildContainer.Components[i] is DataSourceBinding)
                        {
                            DataSourceBinding dataSourceBinding = ChildContainer.Components[i] as DataSourceBinding;
                            if (string.IsNullOrEmpty(dataSourceBinding.PackageName))
                                continue;
                            var ds1 = from c in UTemplates
                                      where c.data_source == dataSourceBinding.Name
                                      select c;
                            // UserQueryProfile uq = QueryProfiles.Find(p => p.DataSourceName == dataSourceBinding.Name);
                            dataSourceBinding.UserTemplates = ds1.ToList();
                        }
                    }
                }
            }
            else
            {

                MasterdataSourceBinding.UserTemplates = new List<fnd_user_profile>();

                if (ChildContainer != null)
                {
                    for (int i = 0; i < ChildContainer.Components.Count; i++)
                    {
                        if (ChildContainer.Components[i] is DataSourceBinding)
                        {
                            DataSourceBinding dataSourceBinding = ChildContainer.Components[i] as DataSourceBinding;

                            dataSourceBinding.UserTemplates = new List<fnd_user_profile>();

                        }
                    }
                }
                //QueryProfile.QueryItems = new List<UserQueryItem>();
                //QueryProfile.PreObject = this.GetType().FullName;
            }
        }
        public void SaveUserTemplatefile(fnd_user_profile QProfile)
        {
            // QProfile.info = QueryProfiles.ToXml();
            if (QProfile.Status == RecordStatus.New)
            {
                FndDAL.UserProfileNew(QProfile);
            }
            else
            {
                FndDAL.UserProfileModify(QProfile);
            }
        }

        private fnd_user_profile WProfile;
        
        protected void LoadWindowProfile()
        {
            WProfile = FndDAL.FindUserProfile(AppEnvironment.Session.USER_ID, this.GetType().FullName, "W");
            if (WProfile == null)
            {
                WProfile = new fnd_user_profile();
                WProfile.identity = AppEnvironment.Session.USER_ID;
                WProfile.pres_object = this.GetType().FullName;
                WProfile.type_flag = "W";
                WProfile.description = this.Text + "-窗口配置";
                WProfile.Status = Core.RecordStatus.New;
                WinProfile = new WindowProfile();
                WinProfile.Behavior = WSBehavior.Empty;
                WinProfile.RecordLimit = 0;
                //WinProfile.
                WinProfile.PreObject = this.GetType().FullName;
                WinProfile.DataSourceItems = new List<DataSourceSetting>();
            }
            else
            {

                WinProfile = WProfile.info.ToXmlEntity<WindowProfile>();
                if (WinProfile.DataSourceItems == null)
                    WinProfile.DataSourceItems = new List<DataSourceSetting>();
                if (WinProfile.RecordLimit != 0)
                    this.MasterdataSourceBinding.RecordLimit = WinProfile.RecordLimit;

            }
        }

        public void SaveWindowProfile()
        {
            WProfile.info = WinProfile.ToXml();
            if (WProfile.Status == RecordStatus.New)
            {
                FndDAL.UserProfileNew(WProfile);
            }
            else
            {
                FndDAL.UserProfileModify(WProfile);
            }
        }
        public void SetMainFunction()
        {
            return;
            foreach (BarItem bi in MainForm.FunctionItems)
            {
                bi.Enabled = IsAvaliable(bi.Name);
            }
        }
        /// <summary>
        /// 是否可用
        /// </summary>
        /// <param name="secObject"></param>
        /// <returns></returns>
        public bool IsAvaliable(string secObject)
        {
            
            return Security.IsAuthorize(AppEnvironment.Session.USER_ID, this.GetType().FullName, secObject, SecObjectType.Button);
            
        }
        public bool IsDataSourceNew(string secObject)
        {
            bool bQuery = Security.IsAuthorize(AppEnvironment.Session.USER_ID, this.GetType().FullName, secObject + ".Query", SecObjectType.DataSource);
            if (!bQuery)
                return bQuery;
            return Security.IsAuthorize(AppEnvironment.Session.USER_ID, this.GetType().FullName, secObject + ".New", SecObjectType.DataSource);
        }
        public bool IsDataSourceDelete(string secObject)
        {
            bool bQuery = Security.IsAuthorize(AppEnvironment.Session.USER_ID, this.GetType().FullName, secObject + ".Query", SecObjectType.DataSource);
            if (!bQuery)
                return bQuery;
            return Security.IsAuthorize(AppEnvironment.Session.USER_ID, this.GetType().FullName, secObject + ".Delete", SecObjectType.DataSource);
        }
        public bool IsDataSourceModify(string secObject)
        {
            bool bQuery = Security.IsAuthorize(AppEnvironment.Session.USER_ID, this.GetType().FullName, secObject + ".Query", SecObjectType.DataSource);
            if (!bQuery)
                return bQuery;
            return Security.IsAuthorize(AppEnvironment.Session.USER_ID, this.GetType().FullName, secObject + ".Modify", SecObjectType.DataSource);
        }
        public bool IsDataSourceNew()
        {
            if (currentSourceBinding == null)
                return true;
            return currentSourceBinding.IsUserNew;
        }
        public bool IsDataSourceDelete()
        {
            if (currentSourceBinding == null)
                return true;
            return this.currentSourceBinding.IsUserDelete;
        }
        public bool IsDataSourceModify()
        {
            if (currentSourceBinding == null)
                return true;
            return this.currentSourceBinding.IsUserModify;
        }
        public bool IsDataSourceQuery()
        {
            if (currentSourceBinding == null)
                return true;
            return this.currentSourceBinding.IsUserQuery;
            
        }
        public bool IsDataSourceQuery(string secObject)
        {
            
            return Security.IsAuthorize(AppEnvironment.Session.USER_ID, this.GetType().FullName, secObject + ".Query", SecObjectType.DataSource);

        }
        protected void LoadMenuAvaliable()
        {
            foreach (ToolStripMenuItem mi in AllMenuItems)
            {
                if (mi.Tag != null)
                    mi.Enabled = IsMenuAvaliable(mi.Tag.ToString());
                else
                    mi.Enabled = IsMenuAvaliable(mi.Name);
            }
        }

        protected void SetMenuAvaliable()
        {
            foreach (ToolStripMenuItem mi in AllMenuItems)
            {
                bool IsAvaliable = false;
                if (mi.Tag != null)
                {
                    IsAvaliable = IsMenuAvaliable(mi.Tag.ToString());
                    
                }
                else
                {
                    
                   IsAvaliable = IsMenuAvaliable(mi.Name);
                }
                if (!IsAvaliable)
                    mi.Enabled = IsAvaliable;
            }
        }
        public Control GetCurrentDSGrid()
        {
            foreach(Control ctrl in ControlList)
            {
                if (ctrl is cGridControl)
                {
                    cGridControl grid = ctrl as cGridControl;
                    DataSourceBinding dsb = grid.DataSource as DataSourceBinding;
                    if (dsb != null && dsb.Equals(this.currentSourceBinding))
                        return ctrl;
                }
            }
            return null;
        }
        /// <summary>
        /// 是否可用
        /// </summary>
        /// <param name="secObject"></param>
        /// <returns></returns>
        public bool IsMenuAvaliable(string secObject)
        {
            return Security.IsAuthorize(AppEnvironment.Session.USER_ID, this.GetType().FullName, secObject, SecObjectType.MenuItem);
        }
        private List<ToolStripMenuItem> AllMenuItems = new List<ToolStripMenuItem>();
        protected void AddFunctionItem()
        {
            //if (this.MainForm != null)
            //{
            //    foreach (BarItem bi in MainForm.FunctionItems)
            //    {
            //        AddUserFunction(bi.Name, SecObjectType.Button, bi.Caption, UpdatesSql.Standard);
            //    }
            //}
            AddUserFunction(this.GetType().FullName, SecObjectType.Window, this.Text, UpdatesSql.Standard);
            if (ChildContainer != null)
            {
                for (int i = 0; i < ChildContainer.Components.Count; i++)
                {
                    if (ChildContainer.Components[i] is cContextMenu)
                    {
                        cContextMenu menus = ChildContainer.Components[i] as cContextMenu;
                        foreach (ToolStripItem tsi in menus.Items)
                            AddMenuItemToList(tsi);
                    }
                }
            }
            //基础菜单不用扫描权限 2014-3-19
            //foreach (ToolStripItem ti in this.BaseMenu.Items)
            //{
            //    AddMenuItemToList(ti);
            //}
            foreach (ToolStripMenuItem mi in AllMenuItems)
            {
                AddUserFunction(mi.Name, SecObjectType.MenuItem, mi.Text, UpdatesSql.Standard);
            }
        }
        public DataItem GetCurrentDataSourceDataItem(string columnName)
        {
            if (currentSourceBinding == null || currentSourceBinding.Columns == null || currentSourceBinding.Columns.Count == 0)
                return null;
            return currentSourceBinding.Columns.Find(p => p.ColumnName == columnName);
        }

        private void AddMenuItemToList(ToolStripItem mi)
        {
            if (mi is ToolStripMenuItem)
            {
                ToolStripMenuItem mItem = mi as ToolStripMenuItem;
                AllMenuItems.Add(mItem);
                if (mItem.DropDownItems != null && mItem.DropDownItems.Count > 0)
                {
                    foreach (ToolStripItem tmi in mItem.DropDownItems)
                    {
                        AddMenuItemToList(tmi);
                    }
                }
            }
        }
        public string GetPictureFilePath(string column)
        {
            foreach (Control ctrl in ControlList)
            {
                if (ctrl is cPictureEdit)
                {
                    cPictureEdit pic = ctrl as cPictureEdit;
                    if (pic.DataColumn != null && pic.DataColumn.ColumnName == column)
                        return pic.FilePath;
                }
            }
            return "";
        }
        public bool GetPictureEditing(string column)
        {
            foreach (Control ctrl in ControlList)
            {
                if (ctrl is cPictureEdit)
                {
                    cPictureEdit pic = ctrl as cPictureEdit;
                    if (pic.DataColumn != null && pic.DataColumn.ColumnName == column)
                        return pic.IsEditing;
                }
                if (ctrl is cGridControl)
                {
                    return true;
                }
            }
            return false;
        }
        protected virtual void AttachToForm(IContainer childContainer)
        {
            if (childContainer == null)
                return;
            for (int i = 0; i < childContainer.Components.Count; i++)
            {
                if (childContainer.Components[i] is DataSourceBinding)
                {
                    DataSourceBinding dataSourceBinding = childContainer.Components[i] as DataSourceBinding;
                    dataSourceBinding.ParentForm = this;
                }
            }


        }
        protected void Session_DataSourceDeleted(object sender, cDataSource.ReturnEventArgsSalBoolean e)
        {
            if (sender is cDataSource)
            {
                cDataSource cds = sender as cDataSource;
                
                SetDeleteStatus(this, cds.IsDelete);
                if(Save)
                    SetRecSelComboBox(false);
                else
                    SetRecSelComboBox(true);
                if (cds.DataSourceBind.Count == 0)
                {
                    SetDataSourceBindCtrlReadOnly( cds.DataSourceBind,true);
                }
            }
        }
        public void RefreshDetailByMasterCurrent()
        {
            if (this.CurrentSourceBinding.Equals(this.MasterdataSourceBinding) || this.CurrentSourceBinding.Details.Count > 0)
            {
                IEntity en = CurrentSourceBinding.Current as IEntity;
                Dictionary<string, object> keys = new Dictionary<string, object>();
                if (en != null)
                {
                    foreach (DataItem di in CurrentSourceBinding.Columns)
                    {
                        if (!keys.ContainsKey(di.ColumnName) && en[di.ColumnName] != null)
                            keys.Add(di.ColumnName, en[di.ColumnName]);

                    }
                }
                Fcdbas.Core.Windows.SalWindow.FireWindowActions(this, Fcdbas.Platform.Const.PM_DataRecordRefresh, CurrentSourceBinding, keys);
            }
        }
        public void UserQuery(DataSourcePopulate nWhat)
        {
            
            try
            {
                if (CurrentSourceBinding.Equals(MasterdataSourceBinding) )
                    MasterdataSourceBinding.RecordLimit = WinProfile.RecordLimit;
                this.CurrentSourceBinding.vrtDataSourceRefresh(nWhat);
                if (CurrentSourceBinding.LogicalParent == null && CurrentSourceBinding.IsLimit && CurrentSourceBinding.Session.RecordCount > CurrentSourceBinding.RecordLimit && CurrentSourceBinding.RecordLimit > 0)
                {
                    dlgAskFetch dlgFetch = new dlgAskFetch(CurrentSourceBinding.Session.RecordCount, CurrentSourceBinding, this);
                    if (dlgFetch.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
                    {
                        SalWindow.FireWindowActions(this, Const.PM_DataSourceRefresh, dlgFetch.FetchMode, this.CurrentSourceBinding.Identify);
                    }
                }
                //else if (!CurrentSourceBinding.Equals(MasterdataSourceBinding))
                //    SalWindow.FireWindowActions(this, Const.PM_DataSourceRefresh, 2,CurrentSourceBinding.Identify);
                if (this.CurrentSourceBinding.Equals(this.MasterdataSourceBinding) || this.CurrentSourceBinding.Details.Count > 0)
                {
                    IEntity en = CurrentSourceBinding.Current as IEntity;
                    Dictionary<string, object> keys = new Dictionary<string, object>();
                    if (en != null)
                    {
                        foreach (DataItem di in CurrentSourceBinding.Columns)
                        {
                            if (!keys.ContainsKey(di.ColumnName) && en[di.ColumnName] != null)
                                keys.Add(di.ColumnName, en[di.ColumnName]);

                        }
                    }
                    Fcdbas.Core.Windows.SalWindow.FireWindowActions(this, Fcdbas.Platform.Const.PM_DataRecordRefresh, CurrentSourceBinding, keys);
                }
            }
            catch (Exception ex)
            {
            }
            finally
            {
                //if (this.CurrentSourceBinding.Equals(this.MasterdataSourceBinding))
                //{
                //    ClearDetailData();
                //}
            }
            
        }
        /// <summary>
        /// 根据Key和条件打开一个新的窗口
        /// </summary>
        /// <param name="sNavKey"></param>
        /// <param name="lsUserWhere"></param>
        public void SalCreateWindow(SalString sNavKey, SalString lsUserWhere)
        {
            MainForm.OpenModule(sNavKey, lsUserWhere,false,true);
        }

        /// <summary>
        /// info字段就是保存的标准字符串, 框架提供接口(新增): this.SalCreateWindowWithNew( SalString sPresObject, SalString sDatasource, SalString sAttr ), 类似的过程如下:
        //1.1: 类似SalCreateWindow, 先打开界面;
        //1.2: 然后类似调用模板的过程, 创建新记录, 只有传入的字符串等于 MainDataSourceBinding的时候才会执行,否则其他的时候直接打开界面就完事了,不再执行按模板新建的功能.
        /// </summary>
        /// <param name="sPresObject"></param>
        /// <param name="sDatasource"></param>
        /// <param name="sAttr"></param>
        public void SalCreateWindowWithNew(SalString sPresObject, SalString sDatasource, SalString sAttr)
        {
            BaseForm frm = MainForm.OpenModule(sPresObject, "", false);
            if (frm.MasterdataSourceBinding.Name != sDatasource)
                return;
            if (frm.MasterdataSourceBinding.Updates == Platform.Enums.UpdatesSql.ReadOnly || !frm.MasterdataSourceBinding.AllowNew)
            {
                this.ShowMessage("不允许新增记录");
                return;
            }
            SalWindow.FireWindowActions(frm, Const.PM_DataRecordNew, 1, frm.MasterdataSourceBinding.Identify);
            SalWindow.FireWindowActions(frm, Const.PM_DataSourceReBinding, 1, frm.MasterdataSourceBinding.Identify);
           // frm.IsCreateWithNew = true;
            IEntity en = frm.MasterdataSourceBinding.Current as IEntity;
            if (en == null)
                return;

            WinUtil.Paste(en, sAttr, frm.MasterdataSourceBinding);
            frm.MasterdataSourceBinding.ResetCurrentItem();
            MainForm.EnableSave = true;
        }
        protected void AdjustMenu()
        {
            //int nCount = this.baseLinks.Count ;
            //List<BarItem> childItems = new List<BarItem>();
            //for (int i = nCount ; i < this.BaseMenu.LinksPersistInfo.Count; i++)
            //{
            //    childItems.Add(this.BaseMenu.LinksPersistInfo[i].Item);
            //    if (this.BaseMenu.LinksPersistInfo[i].BeginGroup)
            //        menuBeginGroups.Add(this.BaseMenu.LinksPersistInfo[i].Item);
            //}
            //this.BaseMenu.ClearLinks();
            //this.BaseMenu.LinksPersistInfo.Clear();
            //this.BaseMenu.ItemLinks.Clear();
            
            //foreach (BarItem bi in childItems)
            //{
            //    BarItemLink link = this.BaseMenu.AddItem(bi);
            //    if (menuBeginGroups.Find(p => p.Name == bi.Name) != null)
            //        link.BeginGroup = true;
                
            //}
           
            //foreach (BarItem bi in baseLinks)
            //{
            //    BarItemLink link = this.BaseMenu.AddItem(bi);
            //    if (menuBeginGroups.Find(p => p.Name == bi.Name) != null)
            //        link.BeginGroup = true;
            //}
            //for (int i = 0; i < baseLinks.Count; i++)
            //{
            //    this.BaseMenu.ItemLinks.Remove(baseLinks[i]);
            //}
            //int nIdx = 0;
            //for(int i = 0; i < this.BaseMenu.LinksPersistInfo.Count && nIdx < links.Length ; i++)
            //{
            //    links[nIdx] =  new DevExpress.XtraBars.LinkPersistInfo(this.BaseMenu.LinksPersistInfo[i].Item);
            //    links[nIdx].Item.Id = nIdx;
            //    nIdx++;
            //}
            
            //for (int i = 0; i < baseLinks.Count  && nIdx < links.Length; i++)
            //{
            //    links[nIdx] = new DevExpress.XtraBars.LinkPersistInfo(baseLinks[i].Item); 
            //    links[nIdx].Item.Id = nIdx;
            //    nIdx++;
            //}
            //this.BaseMenu.LinksPersistInfo.Clear();
            //this.BaseMenu.LinksPersistInfo.AddRange(links);
           
            if (this is cDialogWindow)
            {
                misTemplate.Visible = false;
                miSaveTemplate.Visible = false;
            }
        }

        public void MergeMenu(ContextMenuStrip ChildMenu)
        {

            //List<BarItem> childmenuBeginGroups = new List<BarItem>();
            //List<BarItem> childItems = new List<BarItem>();
            //for (int i = 0; i < ChildMenu.LinksPersistInfo.Count; i++)
            //{
            //    childItems.Add(ChildMenu.LinksPersistInfo[i].Item);
            //    if (ChildMenu.LinksPersistInfo[i].BeginGroup)
            //        childmenuBeginGroups.Add(ChildMenu.LinksPersistInfo[i].Item);
            //}
            
            //foreach (BarItem bi in childItems)
            //{
            //    BarItemLink link = ChildMenu.AddItem(bi);

            //    if (childmenuBeginGroups.Find(p => p.Name == bi.Name) != null)
            //        link.BeginGroup = true;

            //}
            ChildMenu.Items.Add( new ToolStripSeparator());

            for (int i = 0; i < this.BaseMenu.Items.Count; i++ )
            {
                ToolStripItem sItem = BaseMenu.Items[i];
                ToolStripItem nItem =CopyMenuItem(BaseMenu.Items[i],ChildMenu.Name );
                if(sItem is ToolStripMenuItem)
                {
                    ToolStripMenuItem sMi = sItem as ToolStripMenuItem;
                    if(sMi.DropDownItems != null && sMi.DropDownItems.Count > 0)
                    {
                        for(int j = 0; j < sMi.DropDownItems.Count ; j++)
                            ((ToolStripMenuItem)nItem).DropDownItems.Add(CopyMenuItem(sMi.DropDownItems[j],ChildMenu.Name));
                    }
                }
                ChildMenu.Items.Add(nItem);
                
            }
            //foreach (BarItem bi in baseLinks)
            //{
            //    BarItemLink link = ChildMenu.AddItem(bi);
            //    if (menuBeginGroups.Find(p => p.Name == bi.Name) != null)
            //        link.BeginGroup = true;
            //}
        }
        private Dictionary<string, ToolStripItem> DicMenu = new Dictionary<string, ToolStripItem>();
        private Dictionary<string, List<ToolStripItem>> DicBaseMenu = new Dictionary<string, List<ToolStripItem>>();
        private ToolStripItem CopyMenuItem(ToolStripItem sMenuItem,string Name)
        {
            ToolStripItem newItem = null;
            if (sMenuItem is ToolStripSeparator)
            {
                newItem = new ToolStripSeparator();
                return newItem;
            }
            BindingFlags mPropertyFlags = BindingFlags.Instance | BindingFlags.Public
                       | BindingFlags.Static | BindingFlags.NonPublic;//筛选
            BindingFlags mFieldFlags = BindingFlags.Static | BindingFlags.NonPublic;
            Type controlType = typeof(ToolStripItem);
            PropertyInfo propertyInfo = controlType.GetProperty("Events", mPropertyFlags);
            if (sMenuItem is ToolStripMenuItem)
            {
                ToolStripMenuItem ti = sMenuItem as ToolStripMenuItem;
                newItem = new ToolStripMenuItem(ti.Text, ti.Image);
                newItem.Name = Name + ti.Name;
                newItem.Tag = ti.Name;
                //AddUserFunction(newItem.Name, SecObjectType.MenuItem, newItem.Text, UpdatesSql.Standard);
                newItem.Enabled = ti.Enabled;
                if (this is cDialogWindow)
                {
                    if (ti.Name == misTemplate.Name)
                        newItem.Visible = false;
                    if (ti.Name == miSaveTemplate.Name)
                        newItem.Visible = false;
                }
                //标准菜单不需要控制权限 2014 普通用户, 标准菜单 + 用户菜单的情况下,标准菜单没有权限了 
              //  newItem.Visible = ti.Visible;
                //if(newItem.Enabled)
                  //  newItem.Enabled = IsMenuAvaliable(ti.Name);
                ((ToolStripMenuItem)newItem).ShortcutKeys = ti.ShortcutKeys;
            }
            if (sMenuItem is ToolStripComboBox)
            {
                ToolStripComboBox ti = sMenuItem as ToolStripComboBox;
                newItem = new ToolStripComboBox(ti.Text);
                
            }
            if (sMenuItem is ToolStripTextBox)
            {
                ToolStripTextBox ti = sMenuItem as ToolStripTextBox;
                newItem = new ToolStripTextBox(ti.Text);

            }
            Type t = newItem.GetType().GetEvent("Click").EventHandlerType;
            EventHandlerList eventHandlerList = (EventHandlerList)propertyInfo.GetValue(sMenuItem, null);//事件列表  
            
            FieldInfo fieldInfo = (typeof(ToolStripItem)).GetField("EventClick", mFieldFlags);
            if (fieldInfo != null)
            {
                Delegate d = eventHandlerList[fieldInfo.GetValue(sMenuItem)];
                if (d != null)
                {
                    MethodInfo method = sMenuItem.GetType().GetEvent("Click").GetAddMethod();
                    newItem.GetType().GetEvent("Click").AddEventHandler(newItem, d);
                }
            }
            if (!DicMenu.ContainsKey(Name) && sMenuItem.Name == "misTemplate")
                DicMenu.Add(Name, newItem);
            if (DicBaseMenu.ContainsKey(sMenuItem.Name))
                DicBaseMenu[sMenuItem.Name].Add(newItem);
            else
            {
                List<ToolStripItem> news = new List<ToolStripItem>();
                news.Add(newItem);
                DicBaseMenu.Add(sMenuItem.Name, news);
            }
            
            return newItem;
        }
        public event EventHandler<DataItemEnterEventArgs> DataItemEnter;
       // public event EventHandler<DataItemEnterEventArgs> DataItemLostFocus;
        public event EventHandler<EventArgs> SaveCompleted;
        public Control FoucsControl
        {
            get
            {
                return FocusDataItem;
            }
        }
        protected Control FocusDataItem;
        internal void FireOnEnterEvent(Control onEnterControl)
        {
            FocusDataItem = onEnterControl;
            if (onEnterControl is IOwningDataSourceBinding)
            {
                DataSourceBinding dataSourceBinding = ((IOwningDataSourceBinding)onEnterControl).OwningDataSourceBinding;
                if (dataSourceBinding == null)
                    return;
                currentSourceBinding = dataSourceBinding;
            }
            
            if (currentSourceBinding != null && DataItemEnter != null && onEnterControl is IReference)
                DataItemEnter.Invoke(this, new DataItemEnterEventArgs(onEnterControl,((IReference)onEnterControl).DataColumn));
            else if (DataItemEnter != null && onEnterControl is cGridControl)
            {
               // DataItemEnter.Invoke(this, new DataItemEnterEventArgs(onEnterControl,null));
                FireOnGridColumn();
            }
            SetMenuEnable();
            AddUserTemplateMenu();
        }
        public void FireOnGridColumn()
        {
            if (FocusDataItem == null)
                return;
            if (FocusDataItem is cGridControl)
            {
                GridView view = ((cGridControl) FocusDataItem).MainView as GridView;

                DataSourceBinding OwningDataSourceBinding = view.DataSource as DataSourceBinding;
                if (OwningDataSourceBinding == null || OwningDataSourceBinding.Columns == null)
                    return;
                DataItem di = OwningDataSourceBinding.Columns.Find(p => p.ColumnName == view.FocusedColumn.FieldName);
                if (di == null)
                    return;

                if (DataItemEnter != null)
                    DataItemEnter.Invoke(this, new DataItemEnterEventArgs(view.FocusedColumn, di, view));
            }
        }
        /// <summary>
        /// 清除指定数据源的当前的数据
        /// </summary>
        /// <param name="dsb"></param>
        public void ClearCurrentData(DataSourceBinding dsb)
        {
            if (dsb == null || dsb.Current == null)
                return;
            IEntity en = dsb.Current as IEntity;
            if (en != null)
            {
                en.Clear();
                if (en.Status == RecordStatus.Normal)
                    en.Status = RecordStatus.Edit;
                
                dsb.ResetCurrentItem();
            }

        }
        /// <summary>
        /// 清除指定数据源的当前的数据,排除不能清除的部分
        /// </summary>
        /// <param name="dsb"></param>
        public void ClearCurrentDataExclude(DataSourceBinding dsb)
        {

            if (dsb == null || dsb.Current == null)
                return;
            List<string> excludes = new List<string>();
            foreach (DataItem dataItem in dsb.Columns)
            {

                // bool editMethodAuthorized = dsb.IsUserModify;
                if (dataItem != null)
                {

                    if (dsb.Updates == UpdatesSql.ReadOnly || !dsb.AllowEdit || dataItem.IsAssist || dataItem.Flags == DataItemFlags.Key || dataItem.Flags == DataItemFlags.ParentKey || dataItem.UpdateOption != DataItemUpdate.Allow)
                    {
                        excludes.Add(dataItem.ColumnName);
                    }
                }
            }
            IEntity en = dsb.Current as IEntity;
            if (en != null)
            {
                en.Clear(excludes);
                if (en.Status == RecordStatus.Normal)
                    en.Status = RecordStatus.Edit;
                dsb.ResetCurrentItem();
            }

        }
        /// <summary>
        /// 清除指定数据源的当前的数据,排除不能清除的部分
        /// </summary>
        /// <param name="dsb"></param>
        public void ClearCurrentDataExclude(DataSourceBinding dsb, List<string> excludes)
        {
            if (dsb == null || dsb.Current == null)
                return;
            IEntity en = dsb.Current as IEntity;
            if (en != null)
            {
                en.Clear(excludes);
                dsb.ResetCurrentItem();
            }

        }
        protected void AddUserTemplateMenu()
        {
            foreach (string name in DicMenu.Keys)
            {
                ToolStripMenuItem misTemplate = DicMenu[name] as ToolStripMenuItem;
                if (currentSourceBinding == null)
                {
                    misTemplate.DropDownItems.Clear();
                    continue;
                }
                misTemplate.DropDownItems.Clear();
                var t = from c in UTemplates
                        where c.data_source == currentSourceBinding.Name
                        select c;
                foreach (fnd_user_profile u in t)
                {
                    ToolStripMenuItem mi = new ToolStripMenuItem(u.description);
                    mi.Click += new EventHandler(mi_Click);
                    mi.Tag = u;
                    misTemplate.DropDownItems.Add(mi);
                }
            }
        }

        void mi_Click(object sender, EventArgs e)
        {
            if (CurrentSourceBinding.Updates == Platform.Enums.UpdatesSql.ReadOnly || !CurrentSourceBinding.AllowNew)
            {
                this.ShowMessage("不允许新增记录");
                return;
            }
            SalWindow.FireWindowActions(this, Const.PM_DataRecordNew, 1, CurrentSourceBinding.Identify);
            SalWindow.FireWindowActions(this, Const.PM_DataSourceReBinding, 1, CurrentSourceBinding.Identify);

            IEntity en = CurrentSourceBinding.Current as IEntity;
            if (en == null)
                return;
            ToolStripMenuItem mi = sender as ToolStripMenuItem;
            if (mi == null || mi.Tag == null)
                return;
            fnd_user_profile u = mi.Tag as fnd_user_profile;
            string attr = u.info;
            WinUtil.Paste(en, attr, currentSourceBinding);
            CurrentSourceBinding.ResetCurrentItem();
            MainForm.EnableSave = true;
        }
        public void FireOnTextChangedEvent(Control onLostFocusControl)
        {
            string columnName = "";
            //string ctrlValue = "";

            if (onLostFocusControl is IReference)
            {
                if (((IReference)onLostFocusControl).DataColumn != null)
                    columnName = ((IReference)onLostFocusControl).DataColumn.ColumnName;
                
            }
            if (string.IsNullOrEmpty(columnName))
                return;
            foreach (Control ctrl in ControlList)
            {
                if (ctrl is IReference)
                {
                    IReference cRef = (IReference)ctrl;
                    
                    DataItem di = cRef.DataColumn;
                    if (di == null)
                        continue;
                    if (string.IsNullOrEmpty(di.RefFunction) )
                        continue;
                    string func = di.RefFunction;
                    string[] pa = func.Split(',');
                    foreach (string s in pa)
                    {
                        if (s.IndexOf("'") >= 0)
                        {
                           // string ts = s.Replace("'", " ").Trim();
                            func = func.Replace(s, "");
                        }
                    }
                    if (func.IndexOf(columnName, StringComparison.OrdinalIgnoreCase) >= 0)
                    {
                        string v = GetRefFunctionValue(di.RefFunction,((IOwningDataSourceBinding)ctrl).OwningDataSourceBinding);
                        if (!string.IsNullOrWhiteSpace(v))
                        {
                            IEntity en = ((IOwningDataSourceBinding)ctrl).OwningDataSourceBinding.Current as IEntity;
                            if (en != null)
                                en[cRef.Column] = v;
                            cRef.Value = v;

                        }
                    }
                }
            }
        }
        private SalString GetRefFunctionValue(string refFunction,DataSourceBinding dsb)
        {
            string FunctionDefine = refFunction;
            int lbracket = refFunction.IndexOf("(");
            int rbracket = refFunction.IndexOf(")");
            string tmp = refFunction.Substring(lbracket + 1, rbracket - lbracket - 1);
           
            string[] pa = tmp.Split(',');
            foreach (string s in pa)
            {
                if (s.IndexOf("'") < 0)
                {
                    foreach (DataItem di in dsb.Columns)
                    {
                        if (s.ToUpper().Trim() == di.ColumnName.ToUpper().Trim())
                        {
                            IEntity en = dsb.Current as IEntity;
                            if (en == null)
                                return "";
                            string ss = "";
                            if (en[di.ColumnName] != null)
                                ss = en[di.ColumnName].ToString();
                            if(di.DataType != typeof(string))
                                FunctionDefine = FunctionDefine.Replace(s,ss);
                            else
                                FunctionDefine = FunctionDefine.Replace(s,"'" + ss + "'");
                        }
                    }
                }
            }
            //List<string> parms = new List<string>();
            //int idx = -1;
            //string sSql = FunctionDefine;
            //idx = FunctionDefine.IndexOf(":=");
            //tmp = "";
            //if (idx > 0)
            //{
            //    tmp = FunctionDefine.Substring(0, idx).Trim();
            //    parms.Add(tmp);
            //    valus.Insert(0, "");
            //    sSql = FunctionDefine.Substring(idx + 2, FunctionDefine.Length - idx - 2);
            //}
            //int lIdx = sSql.IndexOf("(");
            //int rIdx = sSql.IndexOf(")");
            //string spd = sSql.Substring(0, lIdx);
            //tmp = sSql.Substring(lIdx + 1, rIdx - lIdx - 1);
            //string[] pas = tmp.Split(',');
            //foreach (string p in pas)
            //{
            //    parms.Add(p.Replace(':', ' ').Trim());
            //}
            //if (parms.Count != valus.Count)
            //{
            //    this.ShowMessage("函数定义跟界面的参数不一致，请详细检查！", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
            //    return "*#@*";
            //}

            //Dictionary<SalString,Object> dic = new Dictionary<SalString,object> ();
            //idx = 0;
            //foreach (string p in parms)
            //{
            //    dic.Add(p, valus[idx]);
            //    idx++;
            //}
            FunctionDefine = "SELECT " + FunctionDefine + ";";
            SalString result = cSessionManager.GetUserFunctionValue(FunctionDefine);
            return result;
        }
        public event EventHandler<EventArgs> MasterCurrentChanged;
        internal void MasterdataSourceBinding_CurrentChanged(object sender, EventArgs e)
        {
            DataSourceBinding currentChangedBinding = sender as DataSourceBinding;
            if (currentChangedBinding == null)
                return;

            if (currentChangedBinding.DataSource == null ||
                currentChangedBinding.Current == null)
                return;

            //DataRowView current = (DataRowView)currentChangedBinding.Current;
            //if (current.Row["objdeleted"] != null &&
            //    !(current.Row["objdeleted"] is DBNull) &&
            //    (bool)current.Row["objdeleted"])
            //    SetControlEnabled(this, currentChangedBinding, false);
            //else
            SetControlReadOnly(this, currentChangedBinding);
            if (currentChangedBinding.Details.Count > 0 || currentChangedBinding.Equals(this.MasterdataSourceBinding))
            {
                if (MasterCurrentChanged != null)
                    MasterCurrentChanged(currentChangedBinding, e);
            }
        }
        private bool oldIsAutoPopulate = true;
        public void ResetRefreshTag()
        {
            this.DtlCount = 0;
            this.MasterDone = false;
        }
        void BaseForm_WindowActions(object sender, WindowActionsEventArgs e)
        {
            
            switch (e.ActionType)
            {
                case Const.PM_DataSourceSave:
                    SplashScreenManager.ShowForm(this, typeof(SaveSplashScreen), true, true, false);
                    SplashScreenManager.Default.SendCommand(LoadStatus.ShowTitle, "正在保存数据，请稍候...");
                    SplashScreenManager.Default.SendCommand(LoadStatus.ShowProgress, "正在保存数据，请稍候...");
                    BindRelBoxValueToEntitiy();
                    ForceUpdatePicToSource();
                    ForceUpdateGridToSource();
                    if (!ValidateBiz())
                    {
                        e.Handled = true;
                        e.Return = 0;
                    }
                    else
                    {
                        if(!cSessionManager.IsRemote)
                            Fcdbas.WinUI.Common.cSessionManager.DbTransactionBegin();
                    }
                   // SetRecSelComBoBox(this, false);
                    break;
                case Const.AM_DataSourceFieldModified:
                    SetRecSelComboBox(false);
                    if (this.Parent != null)
                    {
                        SalWindow.FireWindowActions(this.MainForm, Const.AM_DataSourceFieldModified, 0, 0);
                    }
                    //清除attr的记录
                    if (currentSourceBinding != null && currentSourceBinding.Current != null)
                    {
                        IEntity en = currentSourceBinding.Current as IEntity;
                        en.EditAttr("");
                    }
                    break;
                case Const.AM_DataSourceMarkRollback:
                    if (this.Parent != null)
                    {
                        SalWindow.FireWindowActions(this.MainForm, Const.AM_DataSourceMarkRollback, 0, 0);
                    }
                    break;
                case Fcdbas.Platform.Const.PM_DataRecordRefresh:
                    //MasterdataSourceBinding.OldEntitys.Clear();
                    DataSourceBinding dsb = e.LParam as DataSourceBinding;
                    if (dsb != null)
                    {
                        EntityList<IEntity> elist = dsb.DataSource as EntityList<IEntity>;
                        if (elist != null)
                        {
                            foreach (IEntity en in elist)
                            {
                                en.Dirtys.Clear();
                                en.ClearAdditionalValues();
                            }
                        }
                        dsb.OldEntitys.Clear();
                    }
                    break;
                case Const.PM_DataSourceRefresh:
                    this.DtlCount = 0;
                    this.MasterDone = false;
                    RefreshDetailByMasterCurrent();
                    SetRecSelComboBox(true);
                    SetDeleteStatus(this, false);
                    //if(!(this is cMasterDetailWindow || this is cContainerTabFormWindow))
                    //    SplashScreenManager.CloseForm(false);
                    //if(this.currentSourceBinding.Details == null || this.currentSourceBinding .Details.Count == 0)
                    //    SplashScreenManager.CloseForm(false);
                    break;
                case Const.PM_DataRecordNew:
                    oldIsAutoPopulate = IsAutoPopulate;
                    IsAutoPopulate = true;
                    //SetRecSelComBoBox(this, false);
                    SetRecSelComboBox(false);
                    
                    ClearDetailData(this.currentSourceBinding);
                    //先复制文本,例如'产品代码';
                    //2. 新增记录,粘贴文本,不要离开焦点;
                    //3. 然后再新增(Ctrl+N或者toolbar的新增按钮);
                    //没有找到具体问题，先注释
                    //if (this.FocusDataItem != null && this.FocusDataItem is cGridControl)
                    //{
                    //    cGridControl grid = this.FocusDataItem as cGridControl;
                    //    GridView view = grid.MainView as GridView;
                    //    view.MovePrev();
                    //}
                    //FireOnGridColumn();
                    break;
                case Const.PM_DataSourceReBinding:
                    ReBindingGrid(this,(SalNumber)e.LParam);
                    IsAutoPopulate = oldIsAutoPopulate;
                    break;
              
                //case Const.PM_DataRecordRemove:
                //    SetDeleteStatus(this,true);
                //    break;
            }
        }
        public void ClearGridEmptyRow()
        {
            foreach (Control ctrl in ControlList)
            {  
                if (ctrl is cGridControl)
                {
                    cGridControl grid = ctrl as cGridControl;
                    if (grid.DataSource == null || !(grid.DataSource is DataSourceBinding))
                        continue;
                    DataSourceBinding dsb = grid.DataSource as DataSourceBinding;
                    if (dsb.DataSource != null && dsb.DataSource is IEntity)
                        dsb.DataSource = null;
                }
            }
        }
        public void SetRecSelComboBox(bool change)
        {
            foreach(Control ctrl in ControlList)
            {
                
                if (ctrl is cRecSelComboBox  )
                {
                    cRecSelComboBox combox = ctrl as cRecSelComboBox;
                    if (combox.OwningDataSourceBinding.Equals(this.CurrentSourceBinding) || combox.OwningDataSourceBinding.Equals(this.MasterdataSourceBinding))
                        combox.SetButtonEnable(change);
                    if (combox.OwningDataSourceBinding.Details.Count > 0)
                    {
                        foreach (DataSourceBinding dsb in combox.OwningDataSourceBinding.Details)
                        {
                            if (dsb.Equals(this.CurrentSourceBinding))
                                combox.SetButtonEnable(change);
                        }
                    }
                }
                if (ctrl is cGridControl)
                {
                    cGridControl grid = ctrl as cGridControl;
                    if (grid.DataSource == null)
                        continue;
                    if (((DataSourceBinding)grid.DataSource).Equals(this.CurrentSourceBinding))
                    {
                        ((GridView)grid.MainView).ClearSorting();
                        ((GridView)grid.MainView).OptionsCustomization.AllowSort = change;
                    }
                }
            }
        }
        public void ClearDetailData(DataSourceBinding currentDsb)
        {
            if (currentDsb.Equals(this.MasterdataSourceBinding) || (currentDsb.Details.Count > 0))
            {
                foreach (DataSourceBinding dsb in currentDsb.Details)
                {
                    dsb.Session.RecordRefresh = true;
                    ResumeBinding(dsb);
                    dsb.Clear();
                    dsb.List.Add(dsb.CreateEntity());
                    dsb.ResetBindings(true);
                    SuspendBinding(dsb);
                    dsb.Session.RecordRefresh = false;
                   // dsb.DataSource = null;
                }
            }
            ClearGridEmptyRow();
        }
        //public void BindToEntity()
        //{
        //    foreach (Control ctrl in ControlList)
        //    {
        //        if (ctrl is cPictureEdit)
        //        {

        //        }
        //    }
        //}
        //public void BindToUI()
        //{
        //}
        protected virtual void InitBind()
        {
            if (!string.IsNullOrEmpty(this.MasterdataSourceBinding.ViewName))
            {
                AddDSProcedure(this.MasterdataSourceBinding.PackageName, this.MasterdataSourceBinding.Updates);
                AddDSSecurity(this.MasterdataSourceBinding.ViewName, SecObjectType.View, "*", this.MasterdataSourceBinding.Updates);
                AddUserFunction(this.MasterdataSourceBinding.Name + ".New", SecObjectType.DataSource, "新增", UpdatesSql.Standard);
                AddUserFunction(this.MasterdataSourceBinding.Name + ".Modify", SecObjectType.DataSource, "修改", UpdatesSql.Standard);
                AddUserFunction(this.MasterdataSourceBinding.Name + ".Query", SecObjectType.DataSource, "查询", UpdatesSql.Standard);
                AddUserFunction(this.MasterdataSourceBinding.Name + ".Delete", SecObjectType.DataSource, "删除", UpdatesSql.Standard);
            }
            this.MasterdataSourceBinding.IsUserNew = this.IsDataSourceNew(this.MasterdataSourceBinding.Name);
            this.MasterdataSourceBinding.IsUserModify = this.IsDataSourceModify(this.MasterdataSourceBinding.Name);
            this.MasterdataSourceBinding.IsUserDelete = this.IsDataSourceDelete(this.MasterdataSourceBinding.Name);
            this.MasterdataSourceBinding.IsUserQuery = this.IsDataSourceQuery(this.MasterdataSourceBinding.Name);
          //  this.MasterdataSourceBinding.IsLimit = true;
            if (ChildContainer != null)
                InitBind(ChildContainer);
            else
            {
                RefreshMasterData();
                if (ChildContainer == null && UIDebug && !(this is cDialogWindow))
                {
                    this.ShowMessage("VS设计器出错，Container 对象为空，请增加一个一个BindingSource，VS会自动修复");
                    return;
                }
                
               // BindRelBoxValue();
            }
        }
        /// <summary>
        /// 挂起数据绑定
        /// </summary>
        /// <param name="dsb"></param>
        public void SuspendBinding(DataSourceBinding dsb)
        {
            for (int i = 0; i < ControlList.Count; i++)
            {
                Control ctrl = ControlList[i];
                if (ctrl.DataBindings != null && ctrl.DataBindings.Count > 0)
                {
                    if (ctrl.DataBindings[0].DataSource.Equals(dsb))
                    {
                        if (ctrl is IOwningDataSourceBinding)
                        {
                            ((IOwningDataSourceBinding)ctrl).OldBinding = ctrl.DataBindings[0];
                            ctrl.DataBindings.Clear();
                        }
                    }
                }
            }
        }
        /// <summary>
        /// 恢复数据绑定
        /// </summary>
        /// <param name="dsb"></param>
        public void ResumeBinding(DataSourceBinding dsb)
        {
            try
            {
                for (int i = 0; i < ControlList.Count; i++)
                {
                    Control ctrl = ControlList[i];
                    if (ctrl.DataBindings != null && ctrl.DataBindings.Count == 0)
                    {
                        if (ctrl is IOwningDataSourceBinding)
                        {
                            if (((IOwningDataSourceBinding)ctrl).OldBinding != null && ((IOwningDataSourceBinding)ctrl).OldBinding.DataSource.Equals(dsb))
                                ctrl.DataBindings.Add(((IOwningDataSourceBinding)ctrl).OldBinding);
                        }

                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        public bool ShowQuery = false;
        /// <summary>
        /// 刷新主表
        /// </summary>
        protected void RefreshMasterData()
        {
            WSBehavior oldBev = WinProfile.Behavior;
            if (this.IsCreateByOth)
            {
                WinProfile.Behavior = WSBehavior.Populate;
                this.MasterdataSourceBinding.IsAutoQuery = true;
            }
            switch (WinProfile.Behavior)
            {
                case WSBehavior.Empty:
                    //清空会导致界面绑定出错
                    //ClearDetailData();
                    SetFormReadOnly(this.IsSysSave);
                    
                    break;
                case WSBehavior.NewRecord:
                     if (MasterdataSourceBinding.Updates == Platform.Enums.UpdatesSql.ReadOnly || !MasterdataSourceBinding.AllowNew)
                     {
                        this.ShowMessage("不允许新增记录");
                        return;
                     }
                    SalWindow.FireWindowActions(this, Const.PM_DataRecordNew, 1, MasterdataSourceBinding.Identify);
                    if (MasterdataSourceBinding.Count == 1)
                        SetControlReadOnly(this, MasterdataSourceBinding);
                    SalWindow.FireWindowActions(this, Const.PM_DataSourceReBinding, 1, MasterdataSourceBinding.Identify);
                    MainForm.EnableSave  = true;
                    break;
                case WSBehavior.ShowQuery:
                    ShowQuery = true;
                   
                    break;
                case WSBehavior.Populate:
                    MasterdataSourceBinding.RecordLimit = WinProfile.RecordLimit;
                    if(UseProfile)
                        MasterdataSourceBinding.UserWhere = WinProfile.UserWhere;
                    if (IsDataSourceQuery(this.MasterdataSourceBinding.Name) && this.MasterdataSourceBinding.IsAutoQuery)
                    {
                        SalWindow.FireWindowActions(this, Const.PM_DataSourceRefresh, 3, this.MasterdataSourceBinding.Identify);
                        if (this.MasterdataSourceBinding.LogicalParent == null && this.MasterdataSourceBinding.IsLimit && this.MasterdataSourceBinding.Session.RecordCount > this.MasterdataSourceBinding.RecordLimit && this.MasterdataSourceBinding.RecordLimit > 0)
                        {
                            dlgAskFetch dlgFetch = new dlgAskFetch(this.MasterdataSourceBinding.Session.RecordCount, this.MasterdataSourceBinding, this);
                            if (dlgFetch.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
                            {
                                SalWindow.FireWindowActions(this, Const.PM_DataSourceRefresh, dlgFetch.FetchMode, this.MasterdataSourceBinding.Identify);
                            }
                        }
                        else
                            SalWindow.FireWindowActions(this, Const.PM_DataSourceRefresh, 2, this.MasterdataSourceBinding.Identify);
                    }
                    SetControlReadOnly(this, MasterdataSourceBinding);
                    break;
            }
            if (this.IsCreateByOth)
                WinProfile.Behavior = oldBev;
            ClearGridEmptyRow();
        }
        private string GetFunctionName(string func_,ref bool standard)
        {
            string func=func_.Trim();
            int idx = func.IndexOf("(");
            standard = true;
            if (idx >= 0)
            {
                func = func.Substring(0, idx);
                standard = false;
            }
            return func;

        }
        protected void AddUserFunction(string secObject, string subType, string desc, UpdatesSql update)
        {
            if (!AppEnvironment.Session.IsRoot)
                return;
            if (string.IsNullOrEmpty(secObject))
                return;
            string forceRd = "False";
            if (update == UpdatesSql.ReadOnly)
                forceRd = "True";
            fnd_object_security objSec = FndObjectFactory.CreateObjectSecurity(this.GetType(), secObject, SecObjectType.Client, subType, desc, forceRd);
            if (FndDAL.FindObjectSecurity(objSec) == null)
            {
                FndDAL.ObjectSecurityNew(objSec);
            }
        }
        protected void AddDSProcedure( string secObject,UpdatesSql update)
        {
            if (string.IsNullOrEmpty(secObject))
                return;
            if (string.IsNullOrEmpty(secObject))
                return;
            bool standard= true;
            string func = GetFunctionName(secObject, ref standard);
            if (!standard)
            {
                AddDSSecurity( func, SecObjectType.Procedure, "新增,或者修改",update);
            }
            else
            {
                AddDSSecurity( func + "_NEW__", SecObjectType.Procedure, "新增",update);
                AddDSSecurity( func + "_MODIFY__", SecObjectType.Procedure, "修改",update);
                AddDSSecurity( func + "_REMOVE__", SecObjectType.Procedure, "删除",update);
            }
        }
        protected void AddDSSecurity(string secObject, string subType, string desc, UpdatesSql update)
        {
            if (!AppEnvironment.Session.IsRoot)
                return;
            if (string.IsNullOrEmpty(secObject))
                return;
            string forceRd = "False";
            if (update == UpdatesSql.ReadOnly)
                forceRd = "True";
            fnd_object_security objSec = FndObjectFactory.CreateObjectSecurity(this.GetType(),secObject,SecObjectType.Database,subType,desc,forceRd);
            if (FndDAL.FindObjectSecurity(objSec) == null)
            {
                FndDAL.ObjectSecurityNew(objSec);
            }
        }
        /// <summary>
        /// 数据保存
        /// </summary>
        public void DataSourceSave()
        {
            SalWindow.FireWindowActions(this, Const.PM_DataSourceSave, 1, 0);
        }
        /// <summary>
        /// 当前数据源增加新记录
        /// </summary>
        public void DataRecordNew()
        {
            DataRecordNew(this.CurrentSourceBinding);
        }
        /// <summary>
        /// 在指定的数据源上新建记录
        /// </summary>
        /// <param name="dsBind"></param>
        public void DataRecordNew(DataSourceBinding dsBind)
        {
            if (dsBind.Updates == Platform.Enums.UpdatesSql.ReadOnly || !dsBind.AllowNew)
            {
                this.ShowMessage("不允许新增记录");
                return;
            }
            if (FocusDataItem != null && FocusDataItem is cGridControl)
            {
                cGridControl grid = FocusDataItem as cGridControl;
                GridView gview = grid.MainView as GridView;
                if (gview != null)
                {
                    gview.ClearSelection();
                }
            }
            SalWindow.FireWindowActions(this, Const.PM_DataRecordNew, 1, dsBind.Identify);
            if (dsBind.Count == 1)
                this.SetControlReadOnly(this, dsBind);
            SalWindow.FireWindowActions(this, Const.PM_DataSourceReBinding, 1, dsBind.Identify);
            if (MainForm != null)
                MainForm.EnableSave = true;
        }
        /// <summary>
        /// 删除指定数据源的记录
        /// </summary>
        /// <param name="dsBind"></param>
        public void DataRecordDelete(DataSourceBinding dsBind)
        {
            if (dsBind.Updates == Platform.Enums.UpdatesSql.ReadOnly || !dsBind.AllowRemove)
            {
                this.ShowMessage("不允许删除记录");
                return;
            }
            if (FocusDataItem != null && FocusDataItem is cGridControl)
            {
                cGridControl grid = FocusDataItem as cGridControl;
                GridView gview = grid.MainView as GridView;
                if (gview != null)
                {
                    int[] select = gview.GetSelectedRows();
                    if (select.Length == 0)
                    {
                        this.ShowMessage("没有选中记录，请选择要删除的记录！", "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }
                    List<IEntity> list = new List<IEntity>();
                    foreach (int idx in select)
                    {
                        IEntity en = gview.GetRow(idx) as IEntity;
                        list.Add(en);
                    }
                    SalWindow.FireWindowActions(this, Const.PM_DataRecordRemove, list, dsBind.Identify);
                    gview.GridControl.RefreshDataSource();
                }
            }
            else
            {
                SalWindow.FireWindowActions(this, Const.PM_DataRecordRemove, dsBind.Current, dsBind.Identify);
            }

            if (MainForm != null)
                MainForm.EnableSave = this.Save;

        }
        /// <summary>
        /// 删除当前数据源的记录
        /// </summary>
        public void DataRecordDelete()
        {

            DataRecordDelete(this.CurrentSourceBinding);
        }
        /// <summary>
        /// 刷新指定数据源的所有子数据
        /// </summary>
        /// <param name="dsBind"></param>
        public void RefreshDetail(DataSourceBinding dsBind)
        {
            if (dsBind == null || dsBind.Current == null)
                return;
            IEntity en = dsBind.Current as IEntity;
            Dictionary<string, object> keys = new Dictionary<string, object>();
            foreach (DataItem di in dsBind.Columns)
            {
                if (!keys.ContainsKey(di.ColumnName) && en[di.ColumnName] != null)
                    keys.Add(di.ColumnName, en[di.ColumnName]);

            }
            Fcdbas.Core.Windows.SalWindow.FireWindowActions(this, Fcdbas.Platform.Const.PM_DataRecordRefresh, dsBind, keys);
        }
        /// <summary>
        /// 取得指定数据源的数据，包含所有子查询
        /// </summary>
        /// <param name="dsBind"></param>
        public void DataSourcePopulateAll(DataSourceBinding dsBind)
        {
            if (dsBind == null )
                return;
            dsBind.DataSourcePopulate(WinUI.Controls.DataSourcePopulate.All);
            RefreshDetail(dsBind);
        }
        protected virtual void InitBind(IContainer childContainer)
        {
            
            for (int i = 0; i < childContainer.Components.Count; i++)
            {
                if (childContainer.Components[i] is DataSourceBinding)
                {
                    DataSourceBinding dataSourceBinding = childContainer.Components[i] as DataSourceBinding;
                    m_salWindow.AddWindowActions(dataSourceBinding);
                    dataSourceBinding.InitDataSource();
                    dataSourceBinding.FetchRowsDone += new EventHandler<cDataSource.ReturnEventArgsSalNumber>(MasterdataSourceBinding_FetchRowsDone);
                    SuspendBinding(dataSourceBinding);
                    if (string.IsNullOrEmpty(dataSourceBinding.ViewName))
                        continue;
                    if (!string.IsNullOrEmpty(dataSourceBinding.ViewName))
                    {
                        AddDSProcedure(dataSourceBinding.PackageName, dataSourceBinding.Updates);
                        AddDSSecurity(dataSourceBinding.ViewName, SecObjectType.View, "*", dataSourceBinding.Updates);
                        AddUserFunction(dataSourceBinding.Name + ".New", SecObjectType.DataSource, "新增", UpdatesSql.Standard);
                        AddUserFunction(dataSourceBinding.Name + ".Modify", SecObjectType.DataSource, "修改", UpdatesSql.Standard);
                        AddUserFunction(dataSourceBinding.Name + ".Query", SecObjectType.DataSource, "查询", UpdatesSql.Standard);
                        AddUserFunction(dataSourceBinding.Name + ".Delete", SecObjectType.DataSource, "删除", UpdatesSql.Standard);
                    }
                    dataSourceBinding.IsUserNew = this.IsDataSourceNew(dataSourceBinding.Name);
                    dataSourceBinding.IsUserModify = this.IsDataSourceModify(dataSourceBinding.Name);
                    dataSourceBinding.IsUserDelete = this.IsDataSourceDelete(dataSourceBinding.Name);
                    dataSourceBinding.IsUserQuery = this.IsDataSourceQuery(dataSourceBinding.Name);
                    //不需要自动刷新
                    //if (dataSourceBinding.IsUserQuery && dataSourceBinding.IsAutoQuery)
                    //{
                    //    SalWindow.FireWindowActions(this, Const.PM_DataSourceRefresh, 3, dataSourceBinding.Identify);
                    //    if (dataSourceBinding.LogicalParent == null && dataSourceBinding.IsLimit && dataSourceBinding.Session.RecordCount > dataSourceBinding.RecordLimit)
                    //    {
                    //        dlgAskFetch dlgFetch = new dlgAskFetch(dataSourceBinding.Session.RecordCount, dataSourceBinding, this);
                    //        if (dlgFetch.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
                    //        {
                    //            SalWindow.FireWindowActions(this, Const.PM_DataSourceRefresh, dlgFetch.FetchMode, dataSourceBinding.Identify);
                    //        }
                    //    }
                    //    else
                    //        SalWindow.FireWindowActions(this, Const.PM_DataSourceRefresh, 2, dataSourceBinding.Identify);
                    //}
                    SetControlReadOnly(this, dataSourceBinding);
                    dataSourceBinding.Session.DataSourceSaveCompleted += new EventHandler(Session_DataSourceSaveCompleted);
                }
            }
            RefreshMasterData();
           
        }
        /// <summary>
        /// 取得控件绑定的binding
        /// </summary>
        /// <param name="control"></param>
        /// <returns></returns>
        protected DataSourceBinding GetBinding(Control control)
        {
            foreach (Binding binding in control.DataBindings)
            {
                if (binding.DataSource is DataSourceBinding)
                {
                    DataSourceBinding dsb = binding.DataSource as DataSourceBinding;
                    return dsb;
                }
            }
            return null;
        }
        /// <summary>
        /// 修改界面成删除状态或者非删除状态
        /// </summary>
        /// <param name="parentControl"></param>
        /// <param name="delete"></param>
        public void SetDeleteStatus(Control parentControl,bool delete)
        {
            foreach (Control control in parentControl.Controls)
            {

                if (control is IReference)
                {
                    DataSourceBinding dsb = GetBinding(control);
                    if (dsb != null && dsb.Equals(this.CurrentSourceBinding))
                    {
                        //if(dsb.Session.IsDelete && delete)
                        //    ((IReference)control).IsDelete = true;
                        //else
                        ((IReference)control).IsDelete = delete;

                    }
                }
               
                
                if ((control is Controls.cPanel ||
                    control is Controls.cTabControl ||
                    control is Controls.cGroupBox ||
                    control is DevExpress.XtraTab.XtraTabPage ||
                    control is System.Windows.Forms.GroupBox ||
                    control is System.Windows.Forms.Panel ||
                    control is DevExpress.XtraEditors.SplitContainerControl ||
                    control is TabPage) &&
                    control.Controls.Count > 0)
                {
                    if (control is DevExpress.XtraEditors.SplitContainerControl)
                    {
                        DevExpress.XtraEditors.SplitContainerControl scc = control as DevExpress.XtraEditors.SplitContainerControl;
                        SetDeleteStatus(scc.Panel1,delete);
                        SetDeleteStatus(scc.Panel2,delete);
                    }
                    else
                        SetDeleteStatus(control,delete);
                }
            }
        }
        protected void SetControlEditing(bool isEdit)
        {
            foreach (Control ctrl in ControlList)
            {

                if (ctrl is IReference)
                {
                    ((IReference)ctrl).IsEditing = isEdit;
                }
                if (ctrl is cGridControl)
                {
                    //cGridControl grid = ctrl as cGridControl;
                    //if (grid.DataSource == null)
                    //    continue;
                    //if (((DataSourceBinding)grid.DataSource).Equals(this.CurrentSourceBinding))
                    //{
                    //    ((GridView)grid.MainView).ClearSorting();
                    //    ((GridView)grid.MainView).OptionsCustomization.AllowSort = change;
                    //}
                }
            }
        }
        /// <summary>
        /// 保存完成触发回调
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Session_DataSourceSaveCompleted(object sender, EventArgs e)
        {
            SalBoolean commited = MasterdataSourceBinding.Session.Committed;
            SalBoolean rollback = cDataSource.NeedRollback;
            if (!rollback)
            {
                if (ChildContainer != null)
                {
                    for (int i = 0; i < ChildContainer.Components.Count; i++)
                    {
                        if (ChildContainer.Components[i] is DataSourceBinding)
                        {
                            DataSourceBinding dataSourceBinding = ChildContainer.Components[i] as DataSourceBinding;
                            if (string.IsNullOrEmpty(dataSourceBinding.PackageName))
                                continue;
                            commited = commited && dataSourceBinding.Session.Committed;

                            SplashScreenManager.Default.SendCommand(LoadStatus.ShowProgress, "正在保存:" +  dataSourceBinding.ViewName + "的数据，请稍候...");

                        }
                    }
                }
            }
            if (commited && !rollback)
            {
                bool SaveSucess = true;
                SplashScreenManager.Default.SendCommand(LoadStatus.ShowProgress, "全部数据已上传，正在提交，请稍候...");
                if (cSessionManager.IsRemote)
                {
                    Fcdbas.DataContract.ExecuteResult result = cSessionManager.BatchExecute();
                    if (result != null && result.Success)
                    {
                         MasterdataSourceBinding.OldEntitys.Clear();
                        for (int i = 0; i < MasterdataSourceBinding.Session.DataSourceBind.List.Count; i++)
                        {
                            IEntity Entity = MasterdataSourceBinding.Session.DataSourceBind.List[i] as IEntity;
                            if (Entity == null || Entity.Status == RecordStatus.Normal)
                                continue;

                            if (Entity.Status == RecordStatus.Delete)
                            {
                                MasterdataSourceBinding.Session.DataSourceBind.List.RemoveAt(i);
                                i--;
                            }
                        }
                        MasterdataSourceBinding.Session.Committed = false;
                        if (ChildContainer != null)
                        {
                            for (int i = 0; i < ChildContainer.Components.Count; i++)
                            {
                                if (ChildContainer.Components[i] is DataSourceBinding)
                                {
                                    DataSourceBinding dataSourceBinding = ChildContainer.Components[i] as DataSourceBinding;
                                    if (dataSourceBinding == null)
                                        continue;
                                    if (string.IsNullOrEmpty(dataSourceBinding.PackageName))
                                        continue;
                                    dataSourceBinding.Session.Committed = false;
                                    dataSourceBinding.OldEntitys.Clear();
                                    for (int j = 0; j < dataSourceBinding.Session.DataSourceBind.List.Count; j++)
                                    {
                                        IEntity Entity = dataSourceBinding.Session.DataSourceBind.List[j] as IEntity;
                                        if (Entity == null || Entity.Status == RecordStatus.Normal)
                                            continue;

                                        if (Entity.Status == RecordStatus.Delete)
                                        {
                                            dataSourceBinding.Session.DataSourceBind.List.RemoveAt(j);
                                            j--;
                                        }

                                    }
                                    dataSourceBinding.Session.RecordRefresh = true;
                                    dataSourceBinding.ResetBindings(false);
                                    dataSourceBinding.Session.RecordRefresh = false;
                                }
                            }
                        }
                    }
                    else
                    {
                        SaveSucess = false;
                        this.Error(cSessionManager.GetSqlLastError());
                        SplashScreenManager.Default.SendCommand(LoadStatus.ShowProgress, "数据保存失败，已经回滚！");
                    }
                }
                else
                {
                    cSessionManager.DbTransactionEnd();
                    MasterdataSourceBinding.OldEntitys.Clear();
                    for (int i = 0; i < MasterdataSourceBinding.Session.DataSourceBind.List.Count; i++)
                    {
                        IEntity Entity = MasterdataSourceBinding.Session.DataSourceBind.List[i] as IEntity;
                        if (Entity == null || Entity.Status == RecordStatus.Normal)
                            continue;

                        if (Entity.Status == RecordStatus.Delete)
                        {
                            MasterdataSourceBinding.Session.DataSourceBind.List.RemoveAt(i);
                            i--;
                        }
                        if (Entity.Status == RecordStatus.Edit || Entity.Status == RecordStatus.New)
                        {
                            Entity.Dirtys.Clear();
                            Entity.ClearAdditionalValues();
                        }
                        Entity.Status = RecordStatus.Normal;
                    }
                    MasterdataSourceBinding.Session.Committed = false;
                    if (ChildContainer != null)
                    {
                        for (int i = 0; i < ChildContainer.Components.Count; i++)
                        {
                            if (ChildContainer.Components[i] is DataSourceBinding)
                            {
                                DataSourceBinding dataSourceBinding = ChildContainer.Components[i] as DataSourceBinding;
                                if (dataSourceBinding == null)
                                    continue;
                                if (string.IsNullOrEmpty(dataSourceBinding.PackageName))
                                    continue;
                                dataSourceBinding.Session.Committed = false;
                                dataSourceBinding.OldEntitys.Clear();
                                for (int j = 0; j < dataSourceBinding.Session.DataSourceBind.List.Count; j++)
                                {
                                    IEntity Entity = dataSourceBinding.Session.DataSourceBind.List[j] as IEntity;
                                    if (Entity == null || Entity.Status == RecordStatus.Normal)
                                        continue;

                                    if (Entity.Status == RecordStatus.Delete)
                                    {
                                        dataSourceBinding.Session.DataSourceBind.List.RemoveAt(j);
                                        j--;
                                    }
                                    if (Entity.Status == RecordStatus.Edit || Entity.Status == RecordStatus.New)
                                    {
                                        Entity.Dirtys.Clear();
                                        Entity.ClearAdditionalValues();
                                    }
                                    Entity.Status = RecordStatus.Normal;
                                }
                                dataSourceBinding.Session.RecordRefresh = true;
                                dataSourceBinding.ResetBindings(false);
                                dataSourceBinding.Session.RecordRefresh = false;
                            }
                        }
                    }
                    if(SplashScreenManager.Default !=null)
                        SplashScreenManager.Default.SendCommand(LoadStatus.ShowProgress, "全部数据已经保存完成！");
                }
                
                SplashScreenManager.CloseForm(false);
                MasterdataSourceBinding.Session.RecordRefresh = true;
                this.MasterdataSourceBinding.ResetBindings(false);
                MasterdataSourceBinding.Session.RecordRefresh = false;
                if (SaveSucess)
                {
                    IsSaveing = 1;
                    SetDeleteStatus(this, false);
                    SetControlEditing(false);
                    SetRecSelComboBox(true);
                //SetRecSelComBoBox(this, true);
                    if (SaveCompleted != null)
                        SaveCompleted(sender, e);
                }
                if (DataSourceSaveCompleted != null)
                {
                    cDataSource.ReturnEventArgsSalBoolean ret = new cDataSource.ReturnEventArgsSalBoolean();
                    ret.ReturnValue = true;
                    DataSourceSaveCompleted(this, ret);
                }
                if(this.IsAutoPopulate)
                    this.RefreshDetailByMasterCurrent();
            }
            else if(rollback)
            {
                IsSaveing = -1;
                cSessionManager.DbTransactionClear();
                SplashScreenManager.Default.SendCommand(LoadStatus.ShowProgress, "数据保存失败，已经回滚！");
                SplashScreenManager.CloseForm(false);
                cDataSource.NeedRollback = false;
                if (DataSourceSaveCompleted != null)
                {
                    cDataSource.ReturnEventArgsSalBoolean ret = new cDataSource.ReturnEventArgsSalBoolean();
                    ret.ReturnValue = false;
                    DataSourceSaveCompleted(this, ret);
                }
                //不成功，不能刷新
               // if (this.IsAutoPopulate)
                 //   this.RefreshDetailByMasterCurrent();
                for (int i = 0; i < MasterdataSourceBinding.Session.DataSourceBind.List.Count; i++)
                {
                    IEntity Entity = MasterdataSourceBinding.Session.DataSourceBind.List[i] as IEntity;
                    if (Entity == null || Entity.Status == RecordStatus.Normal)
                        continue;
                    //if (Entity.Status == RecordStatus.Edit)
                    //{
                    //    IEntity old = MasterdataSourceBinding.OldEntitys.Find(p => p["objid"].ToString() == Entity["objid"].ToString());
                    //    if (old != null)
                    //        Entity.SetAttr(old.GetAttr(false), false);
                    //    Entity.Status = RecordStatus.Normal;
                    //}
                    //else
                        Entity["objversion"] = Entity.OldObjVersion;
                }
                MasterdataSourceBinding.Session.Committed = false;
                if (ChildContainer != null)
                {
                    for (int i = 0; i < ChildContainer.Components.Count; i++)
                    {
                        if (ChildContainer.Components[i] is DataSourceBinding)
                        {
                            DataSourceBinding dataSourceBinding = ChildContainer.Components[i] as DataSourceBinding;
                            if (string.IsNullOrEmpty(dataSourceBinding.PackageName))
                                continue;
                            dataSourceBinding.Session.Committed = false;
                            for (int j = 0; j < dataSourceBinding.Session.DataSourceBind.List.Count; j++)
                            {
                                IEntity Entity = dataSourceBinding.Session.DataSourceBind.List[j] as IEntity;
                                if (Entity == null || Entity.Status == RecordStatus.Normal)
                                    continue;
                                //if (Entity.Status == RecordStatus.Edit)
                                //{
                                //    IEntity old = dataSourceBinding.OldEntitys.Find(p => p["objid"].ToString() == Entity["objid"].ToString());
                                //    if (old != null)
                                //        Entity.SetAttr(old.GetAttr(false), false);
                                //    Entity.Status = RecordStatus.Normal;
                                //}
                                //else
                                    Entity["objversion"] = Entity.OldObjVersion;
                            }
                        }
                    }
                }
            }
        }
        //protected void BindRelBoxValue()
        //{
        //    foreach (Control control in ControlList)
        //    {
        //        if (control is cRecSelComboBox)
        //        {
        //            ((cRecSelComboBox)control).BindValue();
        //        }
        //    }
        //}
        protected void BindRelBoxValueToEntitiy()
        {
            foreach (Control control in ControlList)
            {
                if (control is cRecSelComboBox)
                {
                    ((cRecSelComboBox)control).SetValueToEntity();
                }
            }
        }
        protected virtual IContainer ChildContainer
        {
            get
            {
                if (this.MasterdataSourceBinding.Site == null)
                    return null;
                return this.MasterdataSourceBinding.Site.Container;
            }
        }
        /// <summary>
        /// 进行基本的业务校验
        /// </summary>
        /// <returns></returns>
        public virtual bool ValidateBiz()
        {
            foreach (Control control in ControlList)
            {
                if (!Validate(control))
                    return false;
            }

            return true;
        }
        /// <summary>
        /// 设置只读状态
        /// </summary>
        /// <param name="readOnly"></param>
        public void SetFormReadOnly(bool readOnly,string columnName)
        {
            foreach (Control control in ControlList)
            {
                if (control is IReadOnly && control is IReference)
                {
                    IReference refe = ((IReference)control);
                    if(refe.DataColumn != null && refe.DataColumn.ColumnName == columnName)
                        ((IReadOnly)control).ReadOnly = readOnly;
                }
            }
        }
        /// <summary>
        /// 设置只读状态
        /// </summary>
        /// <param name="readOnly"></param>
        public void SetFormReadOnly(bool readOnly)
        {
            foreach (Control control in ControlList)
            {
                if (control is IReadOnly)
                {
                    ((IReadOnly)control).ReadOnly = readOnly;
                }
            }
        }
        /// <summary>
        /// 设定数据源绑定的控件为只读或者非只读
        /// </summary>
        /// <param name="ownerBinding"></param>
        /// <param name="readOnly"></param>
        public virtual void SetDataSourceBindCtrlReadOnly(DataSourceBinding ownerBinding, bool readOnly)
        {
            foreach (Control control in ControlList)
            {
                if (control is IOwningDataSourceBinding)
                {
                    if (((IOwningDataSourceBinding)control).OwningDataSourceBinding == null ||
                        !((IOwningDataSourceBinding)control).OwningDataSourceBinding.Equals(ownerBinding))
                        continue;
                    if (control is IReadOnly)
                    {
                        ((IReadOnly)control).ReadOnly = readOnly;
                    }
                }
            }
        }
        /// <summary>
        /// 设定指定容器内的所有数据绑定控件为只读
        /// </summary>
        /// <param name="parent"></param>
        /// <param name="ownerBinding"></param>
        public virtual void SetControlReadOnly(Control parent, DataSourceBinding ownerBinding)
        {
            foreach (Control control in parent.Controls)
            {
                if (control is Label || control is cLabel)
                    continue;
                if ((control is Controls.cPanel ||
                   control is Controls.cTabControl ||
                   control is Controls.cGroupBox ||
                   control is TabPage ||
                   control is DevExpress.XtraTab.XtraTabPage ||
                    control is System.Windows.Forms.GroupBox ||
                    control is System.Windows.Forms.Panel ||
                   control is DevExpress.XtraEditors.SplitContainerControl
                   ) &&
                   control.Controls.Count > 0)
                {

                    if (control is DevExpress.XtraEditors.SplitContainerControl)
                    {
                        DevExpress.XtraEditors.SplitContainerControl scc = control as DevExpress.XtraEditors.SplitContainerControl;
                        SetControlReadOnly(scc.Panel1, ownerBinding);
                        SetControlReadOnly(scc.Panel2, ownerBinding);

                    }
                    else
                        SetControlReadOnly(control, ownerBinding);
                }
                //if (control.Controls.Count > 0)
                //    SetControlReadOnly(control, ownerBinding);

                if (control is IOwningDataSourceBinding)
                {
                    if (((IOwningDataSourceBinding)control).OwningDataSourceBinding == null ||
                        !((IOwningDataSourceBinding)control).OwningDataSourceBinding.Equals(ownerBinding))
                        continue;
                    #region Grid
                    if (control is Controls.cGridControl)
                    {
                        Controls.cGridControl dataGridView = ((Controls.cGridControl)control);
                        IEntity en = ownerBinding.Current as IEntity;
                        if (en == null)
                            continue;
                        if (en.Status == RecordStatus.New || ownerBinding.IsAdding )
                        {
                            ((GridView)dataGridView.MainView).OptionsBehavior.Editable = true;
                            bool newMethodAuthorized = ownerBinding.IsUserNew;
                            foreach (GridColumn viewColumn in ((GridView)dataGridView.MainView).Columns)
                            {
                                if (ownerBinding.Columns != null)
                                {
                                    DataItem dataItem = ownerBinding.Columns.Find(p => p.ColumnName == viewColumn.FieldName);
                                    if (dataItem != null)
                                    {
                                        if (dataItem.Flags == DataItemFlags.ParentKey)
                                        {
                                            viewColumn.OptionsColumn.ReadOnly = true;
                                            viewColumn.AppearanceCell.ForeColor = AppEnvironment.AppOption.ReadOnlyColor;
                                        }
                                        else
                                        {
                                            viewColumn.OptionsColumn.ReadOnly = !newMethodAuthorized || !dataItem.Insertable;
                                            
                                        }
                                        if(viewColumn.OptionsColumn.ReadOnly)
                                            viewColumn.AppearanceCell.ForeColor = AppEnvironment.AppOption.ReadOnlyColor;
                                        if (dataItem.IsAssist)
                                            viewColumn.OptionsColumn.ReadOnly = false;
                                    }
                                }
                            }

                           
                        }
                        else
                        {
                            bool editMethodAuthorized = ownerBinding.IsUserModify;
                            //导致不能选择了
                           // ((GridView)dataGridView.MainView).OptionsBehavior.Editable = ownerBinding.AllowEdit;
                            foreach (GridColumn viewColumn in ((GridView)dataGridView.MainView).Columns)
                            {
                                DataItem dataItem = ownerBinding.Columns.Find(p => p.ColumnName == viewColumn.FieldName);
                                if (dataItem == null)
                                    continue;
                                if ((ownerBinding.Updates == UpdatesSql.ReadOnly || !ownerBinding.AllowEdit)&& !dataItem.IsAssist )
                                    viewColumn.OptionsColumn.ReadOnly = true;
                                else
                                {
                                    if (dataItem != null)
                                    {
                                        if (dataItem.Flags == DataItemFlags.ParentKey)
                                            viewColumn.OptionsColumn.ReadOnly = true;
                                        else
                                            viewColumn.OptionsColumn.ReadOnly = !editMethodAuthorized || dataItem.UpdateOption == DataItemUpdate.NotAllowed;
                                        if (viewColumn.OptionsColumn.ReadOnly)
                                            viewColumn.AppearanceCell.ForeColor = AppEnvironment.AppOption.ReadOnlyColor;
                                    }
                                }
                                if (dataItem.IsAssist)
                                    viewColumn.OptionsColumn.ReadOnly = false;
                            }
                        }
                    }
                    #endregion
                    else
                    {
                       
                        IEntity en = ownerBinding.Current as IEntity;
                        if (en == null)
                            continue;
                        if (en.Status == RecordStatus.New || ownerBinding.IsAdding)
                        {
                            Color originalColor = control.BackColor;
                            bool newMethodAuthorized = ownerBinding.IsUserNew;
                           
                            DataItem dataItem = ((IOwningDataSourceBinding)control).BindingItem;
                            if (dataItem != null)
                            {
                                if (control is IReadOnly)
                                {
                                    ((IReadOnly)control).ReadOnly = !newMethodAuthorized || !dataItem.Insertable;
                                    if (dataItem.IsAssist)
                                        ((IReadOnly)control).ReadOnly = false;
                                }
                                else
                                    control.Enabled = dataItem.Insertable;

                                control.BackColor = originalColor;
                                continue;
                            }
                           
                        }
                        else
                        {
                            if (control is IReference)
                            {
                                string columnName = ((IReference)control).Column;
                                if (string.IsNullOrEmpty(columnName))
                                    continue;

                                Color originalColor = control.BackColor;
                                DataItem dataItem = ((IOwningDataSourceBinding)control).BindingItem;
                                bool editMethodAuthorized = ownerBinding.IsUserModify;
                                if (dataItem != null)
                                {
                                    if (control is IReadOnly)
                                    {
                                        if (ownerBinding.Updates == UpdatesSql.ReadOnly || !ownerBinding.AllowEdit)
                                        {
                                            ((IReadOnly)control).ReadOnly = true;
                                            control.Refresh();
                                        }
                                        else
                                            ((IReadOnly)control).ReadOnly = !editMethodAuthorized || dataItem.UpdateOption == DataItemUpdate.NotAllowed;
                                        if (dataItem.IsAssist)
                                            ((IReadOnly)control).ReadOnly = false;
                                    }
                                    else
                                        control.Enabled = dataItem.UpdateOption != DataItemUpdate.NotAllowed;
                                }
                            }
                        }
                        
                    }
                }
            }
        }
        /// <summary>
        /// 强制把网格的数据压入数据源（网格需要焦点变换才会触发数据绑定）
        /// </summary>
        protected void ForceUpdateGridToSource()
        {
            foreach (Control ctrl in ControlList)
            {
                if (ctrl is cGridControl)
                {
                    cGridControl grid = ctrl as cGridControl;
                    GridView view = grid.MainView as GridView;
                    bool b = view.PostEditor();
                    Console.WriteLine(b.ToString());
                }
            }
        }
        /// <summary>
        /// 强制把图片的数据压入数据源
        /// </summary>
        protected void ForceUpdatePicToSource()
        {
            foreach (Control ctrl in ControlList)
            {
                if (ctrl is cPictureEdit)
                {
                    ((cPictureEdit)ctrl).PostEdit();
                }
            }
        }
        /// <summary>
        /// 进行基本数据的有效性效验
        /// </summary>
        /// <param name="control"></param>
        /// <returns></returns>
        public virtual bool Validate(Control control)
        {
            if (control is IValidate)
            {
                IOwningDataSourceBinding dsb = control as IOwningDataSourceBinding;
                if (dsb != null && dsb.OwningDataSourceBinding != null)
                    if (!(dsb.OwningDataSourceBinding.Session.IsDelete || dsb.OwningDataSourceBinding.Session.IsEdit || dsb.OwningDataSourceBinding.Session.IsNew))
                        return true;
                if (!((IValidate)control).Validate())
                {
                    if (!(control is Controls.cGridControl))
                        control.Focus();

                    return false;
                }
            }

            return true;
        }

        private void BaseForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if(winUtil != null)
                winUtil.SaveGridLayouts(this);
            if (IsSysSave && Save && e.CloseReason != CloseReason.MdiFormClosing)
            {
                if (this.ShowMessage("数据已经修改，是否关闭当前窗口？", "", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == System.Windows.Forms.DialogResult.No)
                {
                    e.Cancel = true;
                   // e.CloseReason
                }
            }
        }

        public bool Save
        {
            get
            {
                bool save = false;
                if (MasterdataSourceBinding.Session.IsDelete || MasterdataSourceBinding.Session.IsEdit || MasterdataSourceBinding.Session.IsNew)
                    save = true;
                if (ChildContainer != null)
                {
                    for (int i = 0; i < ChildContainer.Components.Count; i++)
                    {
                        if (ChildContainer.Components[i] is DataSourceBinding)
                        {
                            DataSourceBinding dataSourceBinding = ChildContainer.Components[i] as DataSourceBinding;
                            if (string.IsNullOrEmpty(dataSourceBinding.PackageName))
                                continue;
                            if (dataSourceBinding.Session.IsDelete || dataSourceBinding.Session.IsEdit || dataSourceBinding.Session.IsNew)
                                save = true;
                        }
                    }
                }
                return save;
            }
        }
        public bool CurrentDsSave
        {
            get
            {
                bool save = false;
                if (this.currentSourceBinding .Equals(MasterdataSourceBinding) &( MasterdataSourceBinding.Session.IsDelete || MasterdataSourceBinding.Session.IsEdit || MasterdataSourceBinding.Session.IsNew))
                    save = true;
                if (ChildContainer != null)
                {
                    for (int i = 0; i < ChildContainer.Components.Count; i++)
                    {
                        if (ChildContainer.Components[i] is DataSourceBinding)
                        {
                            DataSourceBinding dataSourceBinding = ChildContainer.Components[i] as DataSourceBinding;
                            if (string.IsNullOrEmpty(dataSourceBinding.PackageName))
                                continue;
                            if(dataSourceBinding.Equals(this.currentSourceBinding))
                                if (dataSourceBinding.Session.IsDelete || dataSourceBinding.Session.IsEdit || dataSourceBinding.Session.IsNew)
                                    save = true;
                        }
                    }
                }
                return save;
            }
        }
        public event WindowActionsEventHandler WindowActions
        {
            add
            {
                this.m_salWindow.AddWindowActions(value);
            }
            remove
            {
                this.m_salWindow.RemoveWindowActions(value);
            }
        }
        
        public object Derived
        {
            get { return _derived; }
        }

        public void AttachMessageActions(ISalWindow target)
        {
            this.m_salWindow.AddWindowActions(target);
        }

        public void DefaultWndProc(ref Message m)
        {
            base.WndProc(ref m);
        }

        public SalWindow GetSalWindowImpl()
        {
            return this.m_salWindow;
        }

        public int GetWindowType()
        {
            return 1;
        }
        protected virtual void SetRecSelComBoBox(Control parentControl,bool NewRecord)
        {
            foreach (Control control in parentControl.Controls)
            {


                if (control is cRecSelComboBox)
                {
                    
                        ((cRecSelComboBox)control).SetButtonEnable(NewRecord);
                        
                }

                if ((control is Controls.cPanel ||
                    control is Controls.cTabControl ||
                    control is Controls.cGroupBox ||
                    control is TabPage ||
                    control is DevExpress.XtraTab.XtraTabPage ||
                     control is System.Windows.Forms.GroupBox ||
                    control is System.Windows.Forms.Panel ||
                    control is DevExpress.XtraEditors.SplitContainerControl
                    ) &&
                    control.Controls.Count > 0)
                {
                    
                    if (control is DevExpress.XtraEditors.SplitContainerControl)
                    {
                        DevExpress.XtraEditors.SplitContainerControl scc = control as DevExpress.XtraEditors.SplitContainerControl;
                        SetRecSelComBoBox(scc.Panel1, NewRecord);
                        SetRecSelComBoBox(scc.Panel2, NewRecord);
                    }
                    else
                        SetRecSelComBoBox(control, NewRecord);
                }


            }
        }
        /// <summary>
        /// 重新绑定网格
        /// </summary>
        /// <param name="parentControl"></param>
        protected virtual void ReBindingGrid(Control parentControl, SalNumber Identify)
        {
            foreach (Control control in parentControl.Controls)
            {
                if (control is cGridControl)
                {
                    cGridControl grid = (cGridControl)control;
                    DataSourceBinding dsb = grid.DataSource as DataSourceBinding;
                    if (dsb != null && dsb.List.Count <= 1 && dsb.Identify == Identify)
                    {
                        grid.DataSource = null;
                        grid.DataSource = dsb;
                    }
                    //if (grid.MainView != null)
                    //{
                    //    GridView view = grid.MainView as GridView;
                    //    view.PopulateColumns();
                    //}
                    //grid.RefreshDataSource();
                }
                if ((control is Controls.cPanel ||
                    control is Controls.cTabControl ||
                    control is Controls.cGroupBox ||
                    control is TabPage ||
                    control is DevExpress.XtraTab.XtraTabPage ||
                     control is System.Windows.Forms.GroupBox ||
                    control is System.Windows.Forms.Panel ||
                     control is DevExpress.XtraEditors.SplitContainerControl
                    ) &&
                    control.Controls.Count > 0)
                {

                    if (control is DevExpress.XtraEditors.SplitContainerControl)
                    {
                        DevExpress.XtraEditors.SplitContainerControl scc = control as DevExpress.XtraEditors.SplitContainerControl;
                        ReBindingGrid(scc.Panel1,Identify);
                        ReBindingGrid(scc.Panel2,Identify);
                        
                    }
                    else
                        ReBindingGrid(control,Identify);
                    
                }


            }

        }
        //private void SetGridControlByProfile(cGridControl grid)
        //{
        //    if (grid == null || grid.DataSource == null)
        //        return;
        //    DataSourceBinding dsb = grid.DataSource as DataSourceBinding;
        //    if (dsb == null)
        //        return;
        //    DataSourceSetting dsSet = WinProfile.DataSourceItems.Find(p => p.Name == dsName);
        //    if (dsSet != null)
        //    {
        //        ItemSetting req = dsSet.RequireItems.Find(p => p.ColumnName == di.ColumnName);
        //        if (req != null)
        //        {
        //            di.Required = req.IsSet;
        //        }
        //        ItemSetting ronly = dsSet.ReadOnlyItems.Find(p => p.ColumnName == di.ColumnName);
        //        if (ronly != null)
        //        {
        //            if (ronly.IsSet)
        //            {
        //                di.UpdateOption = DataItemUpdate.NotAllowed;
        //            }
        //        }
        //    }
        //    ///增加必须输入的颜色高亮
        //    if (di.Required)
        //    {
        //        if (control is IControl)
        //        {
        //            IControl ctrl = control as IControl;
        //            if (ctrl.BindLabel != null)
        //                ctrl.BindLabel.ForeColor = AppEnvironment.AppOption.MandatoryColor;
        //        }
        //    }
        //}
        /// <summary>
        /// 取得控件的DataItem(数据描述）
        /// </summary>
        /// <param name="control"></param>
        /// <returns></returns>
        private DataItem GetBindingDataItem(Control control)
        {
            DataItem di = null;
            string dsName = "";
            DataSourceBinding dsb = null;
            if (control is cRecSelComboBox)
            {
                cRecSelComboBox rsb = control as cRecSelComboBox;
                dsb = rsb.DataSource as DataSourceBinding;
                if (dsb.Columns != null)
                {
                    di = dsb.Columns.Find(p => p.ColumnName == rsb.Column);
                    dsName = dsb.Name;
                }
            }
            foreach (Binding binding in control.DataBindings)
            {
                if (binding.DataSource is DataSourceBinding)
                {
                    dsb = binding.DataSource as DataSourceBinding;
                    if (dsb.Columns != null)
                    {
                        di = dsb.Columns.Find(p => p.ColumnName == binding.BindingMemberInfo.BindingMember);
                        dsName = dsb.Name;
                        break;
                    }
                }
            }
            if (di != null)
            {
                DataSourceSetting dsSet = WinProfile.DataSourceItems.Find(p => p.Name == dsName);
                if(dsSet != null)
                {
                    ItemSetting req = dsSet.RequireItems.Find(p => p.ColumnName == di.ColumnName);
                    if (req != null)
                    {
                        di.Required = req.IsSet;
                    }
                    ItemSetting ronly = dsSet.ReadOnlyItems.Find(p =>p.ColumnName == di.ColumnName);
                    if (ronly != null)
                    {
                        if (ronly.IsSet)
                        {
                            di.UpdateOption = DataItemUpdate.NotAllowed;
                        }
                    }
                }
                ///增加必须输入的颜色高亮
                ///例如这里的Label是红色的. 你做一个修改. 如果这个字段不可以修改或者新增, 也就是这个字段是'只读', 当然,包括界面是只读的情况下, 不用显示颜色
               // if (di.Required )
                if (di.Required && dsb.Updates != UpdatesSql.ReadOnly && di.Insertable )
                {
                    if (control is IControl)
                    {
                        IControl ctrl = control as IControl;
                        if (ctrl.BindLabel != null)
                            ctrl.BindLabel.ForeColor = AppEnvironment.AppOption.MandatoryColor;
                    }
                }
                if (di.DataType == typeof(DateTime))
                {
                    switch(di.FormatOption.ToUpper())
                    {
                        case "TIME":
                            if(!string.IsNullOrEmpty(AppEnvironment.AppOption.TimeFormat))
                                di.CustomerFormat = AppEnvironment.AppOption.TimeFormat;
                            break;
                        case "DATETIME":
                             if(!string.IsNullOrEmpty(AppEnvironment.AppOption.DateTimeFormat))
                                di.CustomerFormat = AppEnvironment.AppOption.DateTimeFormat;
                            break;
                        default:
                             if(!string.IsNullOrEmpty(AppEnvironment.AppOption.DateFormat))
                                di.CustomerFormat = AppEnvironment.AppOption.DateFormat;
                            break;
                    }
                    di.Alignment = (int)AppEnvironment.AppOption.DAlign.Value;
                }
                else if (di.DataType == typeof(decimal) ||
                   di.DataType == typeof(double) ||
                   di.DataType == typeof(Int16) ||
                   di.DataType == typeof(int) ||
                   di.DataType == typeof(Int64) ||
                   di.DataType == typeof(Single) ||
                   di.DataType == typeof(UInt16) ||
                   di.DataType == typeof(uint) ||
                   di.DataType == typeof(UInt64))
                {
                    di.Alignment = (int)AppEnvironment.AppOption.NAlign.Value;
                }
                else if(di.DataType == typeof(string))
                {
                    di.Alignment = (int)AppEnvironment.AppOption.SAlign.Value;
                }

            }
            return di;
        }
        private DataItem GetBindingDataItem(cGridControl grid, string columnName)
        {
            if (grid.DataSource == null || !(grid.DataSource is DataSourceBinding))
                return null;
            DataSourceBinding dsb = grid.DataSource as DataSourceBinding;

            DataItem di= dsb.Columns.Find(p => p.ColumnName == columnName);
            if (di != null)
            {
                DataSourceSetting dsSet = WinProfile.DataSourceItems.Find(p => p.Name == dsb.Name);
                if (dsSet != null)
                {
                    ItemSetting req = dsSet.RequireItems.Find(p => p.ColumnName == di.ColumnName);
                    if (req != null)
                    {
                        di.Required = req.IsSet;
                    }
                    ItemSetting ronly = dsSet.ReadOnlyItems.Find(p => p.ColumnName == di.ColumnName);
                    if (ronly != null)
                    {
                        if (ronly.IsSet)
                        {
                            di.UpdateOption = DataItemUpdate.NotAllowed;
                        }
                    }
                }
            }
            return di;
        }
        private void SetGridColumnFormat(GridColumn gc, DataItem di)
        {
            if (gc == null || di == null)
                return;
            gc.AppearanceHeader.Font = new Font(AppEnvironment.AppOption.FontName, AppEnvironment.AppOption.FontSize);
            if (gc.ColumnEdit != null)
            {
                if (di.DataType == typeof(DateTime))
                {
                    DevExpress.XtraEditors.Repository.RepositoryItemDateEdit dateEdit = gc.ColumnEdit as DevExpress.XtraEditors.Repository.RepositoryItemDateEdit;
                    if (dateEdit == null)
                        return;
                    if (di.FormatOption.ToUpper() == "DATETIME")
                    {
                        dateEdit.DisplayFormat.FormatString = "yyyy-MM-dd HH:mm:ss";
                        dateEdit.DisplayFormat.FormatType = DevExpress.Utils.FormatType.Custom;
                        dateEdit.EditFormat.FormatString = "yyyy-MM-dd HH:mm:ss";
                        dateEdit.EditFormat.FormatType = DevExpress.Utils.FormatType.Numeric;
                        dateEdit.Mask.EditMask = "yyyy-MM-dd HH:mm:ss";
                    }
                    else if (di.FormatOption.ToUpper() == "DATE")
                    {
                        dateEdit.DisplayFormat.FormatString = "yyyy-MM-dd";
                        dateEdit.DisplayFormat.FormatType = DevExpress.Utils.FormatType.Custom;
                        dateEdit.EditFormat.FormatString = "yyyy-MM-dd";
                        dateEdit.EditFormat.FormatType = DevExpress.Utils.FormatType.Numeric;
                        dateEdit.Mask.EditMask = "yyyy-MM-dd";
                    }
                    else if (di.FormatOption.ToUpper() == "TIME")
                    {
                        dateEdit.DisplayFormat.FormatString = "HH:mm:ss";
                        dateEdit.DisplayFormat.FormatType = DevExpress.Utils.FormatType.Custom;
                        dateEdit.EditFormat.FormatString = "HH:mm:ss";
                        dateEdit.EditFormat.FormatType = DevExpress.Utils.FormatType.Numeric;
                        dateEdit.Mask.EditMask = "HH:mm:ss";
                    }
                    if (!string.IsNullOrEmpty(di.CustomerFormat))
                    {
                        dateEdit.DisplayFormat.FormatString = di.CustomerFormat;
                        dateEdit.DisplayFormat.FormatType = DevExpress.Utils.FormatType.Custom;
                        dateEdit.EditFormat.FormatString = di.CustomerFormat;
                        dateEdit.EditFormat.FormatType = DevExpress.Utils.FormatType.Numeric;
                        dateEdit.Mask.EditMask = di.CustomerFormat;
                    }
                }
                else if (di.DataType == typeof(bool) || di.Simple)
                {
                    DevExpress.XtraEditors.Repository.RepositoryItemCheckEdit chkBox = gc.ColumnEdit as DevExpress.XtraEditors.Repository.RepositoryItemCheckEdit;
                    if (chkBox == null)
                        return;
                    chkBox.DisplayValueChecked = "True";
                    chkBox.DisplayValueGrayed = "Gray";
                    chkBox.DisplayValueUnchecked = "False";
                    chkBox.ValueChecked = "True";
                    chkBox.ValueGrayed = "Gray";
                    chkBox.ValueUnchecked = "False";

                }
                else if (di.DataType == typeof(decimal) ||
                  di.DataType == typeof(double) ||
                  di.DataType == typeof(Int16) ||
                  di.DataType == typeof(int) ||
                  di.DataType == typeof(Int64) ||
                  di.DataType == typeof(Single) ||
                  di.DataType == typeof(UInt16) ||
                  di.DataType == typeof(uint) ||
                  di.DataType == typeof(UInt64))
                {
                    DevExpress.XtraEditors.Repository.RepositoryItemTextEdit numEdit = gc.ColumnEdit as DevExpress.XtraEditors.Repository.RepositoryItemTextEdit;
                    if (numEdit == null)
                        return;

                    if (string.IsNullOrEmpty(WinUI.Common.WinUtil.GetFormatMask(di.FormatOption)))
                    {
                        numEdit.Mask.MaskType = DevExpress.XtraEditors.Mask.MaskType.None;
                        numEdit.Mask.EditMask = "";
                        numEdit.Mask.UseMaskAsDisplayFormat = true;
                    }
                    else
                    {
                        numEdit.Mask.MaskType = DevExpress.XtraEditors.Mask.MaskType.Numeric;
                        numEdit.Mask.EditMask = string.IsNullOrEmpty(di.CustomerFormat) ? WinUI.Common.WinUtil.GetFormatMask(di.FormatOption) : di.CustomerFormat;
                        numEdit.Mask.UseMaskAsDisplayFormat = true;
                    }

                }
                else if (di.DataType == typeof(string))
                {
                    DevExpress.XtraEditors.Repository.RepositoryItemTextEdit txtEdit = gc.ColumnEdit as DevExpress.XtraEditors.Repository.RepositoryItemTextEdit;

                    if (di.FormatOption.ToUpper() == "UPPERCASE")
                        txtEdit.CharacterCasing = CharacterCasing.Upper;
                    else if (di.FormatOption.ToUpper() == "LOWERCASE")
                        txtEdit.CharacterCasing = CharacterCasing.Lower;
                }
            }
            else
            {
                if (di.DataType == typeof(DateTime))
                {
                  
                    if (di.FormatOption.ToUpper() == "DATETIME")
                    {
                        gc.DisplayFormat.FormatString = "yyyy-MM-dd HH:mm:ss";
                        gc.DisplayFormat.FormatType = DevExpress.Utils.FormatType.Custom;
                        
                    }
                    else if (di.FormatOption.ToUpper() == "DATE")
                    {
                        gc.DisplayFormat.FormatString = "yyyy-MM-dd";
                        gc.DisplayFormat.FormatType = DevExpress.Utils.FormatType.Custom;
                        
                    }
                    else if (di.FormatOption.ToUpper() == "TIME")
                    {
                        gc.DisplayFormat.FormatString = "HH:mm:ss";
                        gc.DisplayFormat.FormatType = DevExpress.Utils.FormatType.Custom;
                       
                    }
                    if (!string.IsNullOrEmpty(di.CustomerFormat))
                    {
                        gc.DisplayFormat.FormatString = di.CustomerFormat;
                        gc.DisplayFormat.FormatType = DevExpress.Utils.FormatType.Custom;
                       
                    }
                }
               
                else if (di.DataType == typeof(decimal) ||
                  di.DataType == typeof(double) ||
                  di.DataType == typeof(Int16) ||
                  di.DataType == typeof(int) ||
                  di.DataType == typeof(Int64) ||
                  di.DataType == typeof(Single) ||
                  di.DataType == typeof(UInt16) ||
                  di.DataType == typeof(uint) ||
                  di.DataType == typeof(UInt64))
                {
                    
                    if (string.IsNullOrEmpty(WinUI.Common.WinUtil.GetFormatMask(di.FormatOption)))
                    {
                        gc.DisplayFormat.FormatType = DevExpress.Utils.FormatType.None ;
                       
                    }
                    else
                    {
                        gc.DisplayFormat.FormatType= DevExpress.Utils.FormatType.Numeric;
                        gc.DisplayFormat.FormatString = string.IsNullOrEmpty(di.CustomerFormat) ? WinUI.Common.WinUtil.GetFormatMask(di.FormatOption) : di.CustomerFormat;
                       
                    }

                }
                //else if (di.DataType == typeof(string))
                //{
                //   // DevExpress.XtraEditors.Repository.RepositoryItemTextEdit txtEdit = gc.ColumnEdit as DevExpress.XtraEditors.Repository.RepositoryItemTextEdit;

                //    if (di.FormatOption.ToUpper() == "UPPERCASE")
                //        txtEdit.CharacterCasing = CharacterCasing.Upper;
                //    else if (di.FormatOption.ToUpper() == "LOWERCASE")
                //        txtEdit.CharacterCasing = CharacterCasing.Lower;
                //}
            }
            
        }
        protected virtual void InitControls(Control parentControl)
        {

            foreach (Control control in parentControl.Controls)
            {
                if(! (parentControl is Form ))
                    parentControl.Font = new Font(AppEnvironment.AppOption.FontName, AppEnvironment.AppOption.FontSize);
                control.Font = new Font(AppEnvironment.AppOption.FontName, AppEnvironment.AppOption.FontSize);
                if (control is cGridControl)
                {
                    ControlList.Add(control);
                }
                if (control is cButton)
                {
                    AddUserFunction(control.Name, SecObjectType.Button, control.Text, UpdatesSql.Standard);
                    control.Enabled = IsAvaliable(control.Name);
                }
                if (control is IReference)
                {
                    ControlList.Add(control);
                    if (control.DataBindings != null && control.DataBindings.Count > 0)
                        ((IOwningDataSourceBinding)control).OldBinding = control.DataBindings[0];
                    DataItem dsi = GetBindingDataItem(control);
                    if (dsi != null)
                    {
                        if (!string.IsNullOrEmpty(dsi.RefFunction))
                        {
                            bool kk = false;
                            string func = GetFunctionName(dsi.RefFunction, ref kk);
                            AddDSSecurity(func,SecObjectType.Function,((IReference)control).Label.Replace(":", "").Replace("：", ""),UpdatesSql.Standard);
                        }
                        if (!string.IsNullOrEmpty(dsi.LogicalParent))
                        {
                            string lov = dsi.LogicalParent.SubstringRight(".");
                          //  DataSourceBinding dataSourceBinding = GetBinding(control);
                            AddUserFunction(lov, SecObjectType.LOV, dsi.Caption + "_LOV", UpdatesSql.Standard);
                           // if(dataSourceBinding != null )
                            AddDSSecurity(lov, SecObjectType.View, dsi.Caption + "_LOV", UpdatesSql.Standard);
                           // AddDSSecurity(typeof(Fcdbas.WinUI.Forms.frmMainForm), "fnd_language_code", SecObjectType.View, "*", "False");
                        }
                        if (!string.IsNullOrEmpty(dsi.Reference))
                        {
                            fnd_exp_navigator nav = MainFormPresenter.FindNavigator(dsi.Reference);
                            if (nav != null)
                            {
                                AddUserFunction(nav.pres_object, SecObjectType.Zoom, nav.win_text, UpdatesSql.Standard);
                            }
                        }
                        ((IReference)control).DataColumn = dsi;
                    }

                    if (((IReference)control).DataColumn != null)
                    {
                        if (!string.IsNullOrEmpty(((IReference)control).Label))
                        {
                            string caption = ((IReference)control).Label.Replace(":", "").Replace("：", "");
                            ((IReference)control).DataColumn.Caption = ((IReference)control).Label;
                            DataItem di = MasterdataSourceBinding.Columns.Find(p => p.ColumnName == ((IReference)control).DataColumn.ColumnName);
                            if (di != null)
                            {
                                di.Caption = caption;
                                //VisibleDataItems.Add(di);
                            }
                        }
                    }
                }
                if (control is IEnumMethod)
                    ((IEnumMethod)control).SetEnums();
                if (control is cGridControl)
                {
                    cGridControl grid = (cGridControl)control;
                    
                    if (grid.MainView != null)
                    {
                        GridView view = grid.MainView as GridView;
                        if (view != null)
                        {
                            //导致选择不了单元格的内容
                            //if (grid.DataSource != null && grid.DataSource is DataSourceBinding)
                            //{
                            //    DataSourceBinding ds = grid.DataSource as DataSourceBinding;
                            //    //view.OptionsBehavior.Editable = ds.AllowEdit;
                            //}
                            view.CellValueChanged += new DevExpress.XtraGrid.Views.Base.CellValueChangedEventHandler(view_CellValueChanged);
                            view.CellValueChanging += new DevExpress.XtraGrid.Views.Base.CellValueChangedEventHandler(view_CellValueChanging);
                            view.FocusedColumnChanged += new DevExpress.XtraGrid.Views.Base.FocusedColumnChangedEventHandler(view_FocusedColumnChanged);
                            view.RowCellStyle += new RowCellStyleEventHandler(view_RowCellStyle);
                            view.RowStyle += new RowStyleEventHandler(view_RowStyle);
                            view.GotFocus += new EventHandler(view_GotFocus);
                            view.FocusedRowChanged += new DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventHandler(view_FocusedRowChanged);
                           // view.RowCellClick += new RowCellClickEventHandler(view_RowCellClick);
                        }
                        foreach (GridColumn gc in view.Columns)
                        {
                            DataItem di = GetBindingDataItem(grid,gc.FieldName);
                            if (di != null)
                            {
                                if (!string.IsNullOrEmpty(di.RefFunction))
                                {
                                    bool kk = false;
                                    string func = GetFunctionName(di.RefFunction, ref kk);
                                    AddDSSecurity(func, SecObjectType.Function, gc.Caption, UpdatesSql.Standard);
                                }
                                if (!string.IsNullOrEmpty(di.LogicalParent))
                                {
                                    string lov = di.LogicalParent.SubstringRight(".");
                       
                                    AddUserFunction(lov, SecObjectType.LOV, lov + "_LOV", UpdatesSql.Standard);
                                }
                                if (!string.IsNullOrEmpty(di.Reference))
                                {
                                    fnd_exp_navigator nav = MainFormPresenter.FindNavigator(di.Reference);
                                    if (nav != null)
                                    {
                                        AddUserFunction(nav.pres_object, SecObjectType.Zoom, nav.win_text, UpdatesSql.Standard);
                                    }
                                }
                                SetGridColumnFormat(gc, di);
                                di.Caption = gc.Caption;
                                if (di.Required)
                                    gc.AppearanceHeader.ForeColor = AppEnvironment.AppOption.MandatoryColor;
                                //VisibleDataItems.Add(di);
                            }
                           
                        }
                    }
                }
                if ((control is Controls.cPanel ||
                    control is Controls.cTabControl ||
                    control is Controls.cGroupBox ||
                    control is DevExpress.XtraTab.XtraTabPage ||
                    control is DevExpress.XtraEditors.SplitContainerControl ||
                    control is System.Windows.Forms.GroupBox ||
                    control is System.Windows.Forms.Panel ||
                    
                    control is TabPage) &&
                    control.Controls.Count > 0)
                {
                    if (control is DevExpress.XtraTab.XtraTabPage)
                    {
                        DevExpress.XtraTab.XtraTabPage tp = control as DevExpress.XtraTab.XtraTabPage;
                        tp.Appearance.Header.Font = new Font(AppEnvironment.AppOption.FontName, AppEnvironment.AppOption.FontSize);
                    }
                    if (control is DevExpress.XtraEditors.SplitContainerControl)
                    {
                        DevExpress.XtraEditors.SplitContainerControl scc = control as DevExpress.XtraEditors.SplitContainerControl;
                        InitControls(scc.Panel1);
                        InitControls(scc.Panel2);
                    }
                    else
                        InitControls(control);
                }
            }

           
        }

        void view_RowStyle(object sender, RowStyleEventArgs e)
        {
            GridView view = sender as GridView;
            IEntity en = view.GetRow(e.RowHandle) as IEntity;
            if (en == null)
                return;
            if (en.Status == RecordStatus.Delete)
                e.Appearance.ForeColor = AppEnvironment.AppOption.DeleteColor;
        }

        void view_RowCellStyle(object sender, RowCellStyleEventArgs e)
        {
            GridView view = sender as GridView;
            IEntity en = view.GetRow(e.RowHandle) as IEntity;
            if (en == null)
                return;
            if (en.Dirtys.ContainsKey(e.Column.FieldName) && en.Dirtys[e.Column.FieldName])
            {
                e.Appearance.ForeColor = AppEnvironment.AppOption.EditColor;
            }
        }
        /// <summary>
        /// 0表正在保存，-1失败，1成功
        /// </summary>
        private int IsSaveing = 0;
        private bool IsInteChange = false;
        void view_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            GridView view = sender as GridView;
            if (sender == null)
                return;
            if (IsInteChange)
            {
                IsInteChange = false;
                return;
            }
            DataSourceBinding dsb = view.DataSource as DataSourceBinding;
            if (dsb == null)
                return;
            DataItem di1 = dsb.Columns.Find(p => p.ColumnName == view.FocusedColumn.FieldName);
            if (di1 == null)
                return;
            if (DataItemEnter != null && dsb.Equals(this.currentSourceBinding))
                DataItemEnter.Invoke(this, new DataItemEnterEventArgs(view.FocusedColumn, di1, view));
            
            if (dsb.Details == null || dsb.Details.Count == 0)
                return;
            if (dsb != null)
            {
                bool IsSave = false;
                if (dsb.Session.IsEdit || dsb.Session.IsDelete || dsb.Session.IsNew)
                    IsSave = true;
                if (IsSave)
                    return;

                if (dsb.Details != null)
                {
                    foreach (DataSourceBinding ds in dsb.Details)
                    {

                        if (ds.Session.IsDelete || ds.Session.IsEdit || ds.Session.IsNew)
                            IsSave = true;
                    }
                }
                Form frm = this.FindForm();
                #region save
                if (IsSave)
                {
                    if (WinUI.Common.WinUtil.Translate.ShowMessage("数据已经修改，是否保存？", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                       // Fcdbas.WinUI.Common.cSessionManager.DbTransactionBegin();
                        IsSaveing = 0;
                        Fcdbas.Core.Windows.SalWindow.FireWindowActions(frm, Fcdbas.Platform.Const.PM_DataSourceSave, 1, dsb.Identify);
                        while (true)
                        {
                            System.Threading.Thread.Sleep(500);
                            if (IsSaveing == 1)
                                break;
                            if (IsSaveing == -1)
                            {
                                IsInteChange = true;
                                view.MoveBy(e.PrevFocusedRowHandle-e.FocusedRowHandle );
                                return;
                            }
                        }
                    }
                    else
                    {
                        if (frm != null && frm is BaseForm)
                        {
                            ((BaseForm)frm).SetDeleteStatus(frm, false);
                        }
                        IEntity cn = dsb.Current as IEntity;
                        if (cn != null)
                        {
                            cn.Status = RecordStatus.Normal;
                            IEntity old = dsb.OldEntitys.Find(p => p["objid"].ToString() == cn["objid"].ToString());
                            if (old != null)
                                cn.SetAttr(old.GetAttr(false), false);
                            if (dsb.Details != null)
                            {
                                foreach (DataSourceBinding db in dsb.Details)
                                {
                                   
                                    db.OldEntitys.Clear();
                                }
                            }
                        }
                        Fcdbas.Core.Windows.SalWindow.FireWindowActions(frm, Fcdbas.Platform.Const.AM_DataSourceMarkRollback, 1, dsb.Identify);
                    }
                }
                #endregion

                if (frm != null && !dsb.Session.IsNew )
                {

                    IEntity en = dsb.Current as IEntity;
                    if (en == null)
                        return;
                    Dictionary<string, object> keys = new Dictionary<string, object>();
                    foreach (DataItem di in dsb.Columns)
                    {
                        if (!keys.ContainsKey(di.ColumnName) && en[di.ColumnName] != null)
                            keys.Add(di.ColumnName, en[di.ColumnName]);

                    }
                    Fcdbas.Core.Windows.SalWindow.FireWindowActions(frm, Fcdbas.Platform.Const.PM_DataRecordRefresh, dsb, keys);
                }
               

            }
        }

        void view_GotFocus(object sender, EventArgs e)
        {
            if (sender == null)
                return;
            GridView view = sender as GridView;
            
            DataSourceBinding OwningDataSourceBinding = view.DataSource as DataSourceBinding;
            if (OwningDataSourceBinding == null || OwningDataSourceBinding.Columns == null)
                return;
            if (view.FocusedColumn == null)
                return;
            DataItem di = OwningDataSourceBinding.Columns.Find(p => p.ColumnName == view.FocusedColumn.FieldName);
            if (di == null)
                return;
            
          //  if (DataItemEnter != null)
           //     DataItemEnter.Invoke(this, new DataItemEnterEventArgs(view.FocusedColumn, di,view));
        }

        

        

        void view_FocusedColumnChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedColumnChangedEventArgs e)
        {
            if (sender == null)
                return;
            GridView view = sender as GridView;
            
            DataSourceBinding OwningDataSourceBinding = view.DataSource as DataSourceBinding;
            if (OwningDataSourceBinding == null || OwningDataSourceBinding.Columns == null)
                return;
            DataItem di = OwningDataSourceBinding.Columns.Find(p => p.ColumnName == e.FocusedColumn.FieldName);
            if(di == null)
                return;

            if (DataItemEnter != null)
                DataItemEnter.Invoke(this, new DataItemEnterEventArgs(e.FocusedColumn, di,view));
        }
        public void SetReference(DataSourceBinding OwningDataSourceBinding,GridView view,string ColumnName)
        {
            IEntity en = OwningDataSourceBinding.Current as IEntity;
            foreach (DataItem di in OwningDataSourceBinding.Columns)
            {

                if (di == null)
                    continue;
                if (string.IsNullOrEmpty(di.RefFunction))
                    continue;
                string func = di.RefFunction;
                string[] pa = func.Split(',');
                foreach (string s in pa)
                {
                    if (s.IndexOf("'") >= 0)
                    {
                        // string ts = s.Replace("'", " ").Trim();
                        func = func.Replace(s, "");
                    }
                }
                int pos = func.IndexOf("(");
                if (pos < 0)
                    pos = 0;
                if (func.IndexOf(ColumnName,pos, StringComparison.OrdinalIgnoreCase) >= 0)
                {
                    string v = GetRefFunctionValue(di.RefFunction, OwningDataSourceBinding);

                    if (en != null)
                    {
                        en[di.ColumnName] = v;
                        view.RefreshData();
                        view.RefreshRow(view.FocusedRowHandle);
                    }
                }
            }
        }
        private void view_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
             GridView view = sender as GridView;
            if (sender == null)
                return;
            DataSourceBinding OwningDataSourceBinding = view.DataSource as DataSourceBinding;

            if (OwningDataSourceBinding != null)
            {
                IEntity en = OwningDataSourceBinding.Current as IEntity;
                if (en == null)
                    return;
                SetReference(OwningDataSourceBinding, view, e.Column.FieldName);
                DataItem di = OwningDataSourceBinding.Columns.Find(p => p.ColumnName == e.Column.FieldName);
                if (di != null && di.IsAssist)
                    return;
                if (!OwningDataSourceBinding.Binding && !OwningDataSourceBinding.Session.RecordRefresh)
                {
                    view.ClearSelection();
                    Form frm = view.GridControl.FindForm();
                    if (frm != null)
                        Fcdbas.Core.Windows.SalWindow.FireWindowActions(frm, Fcdbas.Platform.Const.AM_DataSourceFieldModified, 1, OwningDataSourceBinding.Identify);
                }
                
            }
        }

        void view_CellValueChanging(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            GridView view = sender as GridView;
            if (sender == null)
                return;
            if (e.RowHandle < 0)
                return;
            DataSourceBinding OwningDataSourceBinding = view.DataSource as DataSourceBinding;
            
            if (OwningDataSourceBinding != null)
            {
                if (OwningDataSourceBinding.Updates == Platform.Enums.UpdatesSql.ReadOnly)
                    return;
                //if (!OwningDataSourceBinding.AllowEdit)
                //    return;
                DataItem di = OwningDataSourceBinding.Columns.Find(p => p.ColumnName == e.Column.FieldName);
                if (di != null && di.IsAssist)
                    return;
                Fcdbas.Core.IEntity en = OwningDataSourceBinding.Current as Fcdbas.Core.IEntity;
                if (en == null)
                    return;
                
                if (en.Status == Core.RecordStatus.Normal && !OwningDataSourceBinding.Binding && !OwningDataSourceBinding.Session.RecordRefresh)
                {
                    OwningDataSourceBinding.vrtDataSourceFieldModified();
                    if (MainForm != null)
                        MainForm.EnableSave = true;
                }
                try
                {
                    if (e.Value != null)
                    {
                        if (e.Value is Image)
                        {
                            Bitmap bm = e.Value as Bitmap;
                            en[e.Column.FieldName] = Fcdbas.Core.Util.BitmapHelper.BitmapToBytes(bm);

                        }
                        else
                        {

                            en[e.Column.FieldName] = e.Value;
                        }
                    }
                    else
                        en[e.Column.FieldName] = e.Value;
                    en.EditAttr("");
                }
                catch (Exception ex)
                {
                    Fcdbas.WinUI.Common.WinTranslate.GetTranslate().ShowMessage(ex.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                view.RefreshRowCell(e.RowHandle, e.Column);
                if (view.OptionsCustomization.AllowSort)
                {
                    view.ClearSorting();
                    view.OptionsCustomization.AllowSort = false;
                    view.SelectCell(e.RowHandle, e.Column);
                    view.ShowEditorByMouse();
                    DevExpress.XtraEditors.Repository.RepositoryItemTextEdit numEdit = e.Column.ColumnEdit as DevExpress.XtraEditors.Repository.RepositoryItemTextEdit;
                    if (numEdit != null)
                    {
                        if (!(numEdit.Mask.MaskType == DevExpress.XtraEditors.Mask.MaskType.Numeric && numEdit.Mask.UseMaskAsDisplayFormat == true))
                        {
                            SendKeys.Send("{END}");
                        }
                    }
                    else
                        SendKeys.Send("{END}");
                    //view.ShowEditorByKey(new KeyEventArgs(Keys.A));
                }
            }
        }
        public Form SavedOwner
        {
            get { return this.m_savedOwner; }
        }

        public int ReturnValue
        {
            get
            {
                return this.m_returnValue;
            }
            set
            {
                m_returnValue = value ;
            }
        }
        
        public bool GetState(Fcdbas.Core.Windows.SalFormState state)
        {
            return (this.m_state & state) == state;
        }

        public void SetState(Fcdbas.Core.Windows.SalFormState state, bool flag)
        {
            if (flag)
            {
                this.m_state |= state;
                return;
            }
            this.m_state &= ~state;
        }

        public Control GetLabel(Control ctrl)
        {
            throw new NotImplementedException();
        }

        public void SetLabel(Control ctrl, Control label)
        {
            throw new NotImplementedException();
        }

        //public void Show(Control parent)
        //{
        //    throw new NotImplementedException();
        //}

        //public int ShowDialog(Control parent)
        //{
        //    return ShowDialog(
        //   // throw new NotImplementedException();
        //}

        public void RegisterAccelerator(cButton btn, Keys key)
        {
            if (key == System.Windows.Forms.Keys.None)
            {
                RemoveAccelerator(btn);
                return;
            }
            if (this.m_acceleratorTable == null)
            {
                this.m_acceleratorTable = new System.Collections.Generic.List<System.Collections.Generic.KeyValuePair<System.Windows.Forms.Keys, cButton>>();
            }
            else
            {
                for (int i = 0; i < this.m_acceleratorTable.Count; i++)
                {
                    if (this.m_acceleratorTable[i].Value == btn)
                    {
                        this.m_acceleratorTable[i] = new System.Collections.Generic.KeyValuePair<System.Windows.Forms.Keys, cButton>(key, btn);
                        return;
                    }
                }
            }
            this.m_acceleratorTable.Add(new System.Collections.Generic.KeyValuePair<System.Windows.Forms.Keys, cButton>(key, btn));
        }

        public void RemoveAccelerator(cButton btn)
        {
            if (this.m_acceleratorTable != null)
            {
                for (int i = 0; i < this.m_acceleratorTable.Count; i++)
                {
                    if (this.m_acceleratorTable[i].Value == btn)
                    {
                        this.m_acceleratorTable.RemoveAt(i);
                        return;
                    }
                }
            }
        }

        private void 读取数据ToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void barButtonItem3_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {

        }

        private void BaseForm_MouseDown(object sender, MouseEventArgs e)
        {
            
        }
        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
           // Console.WriteLine(keyData.ToString());
            if ((Control.ModifierKeys & Keys.Control) == Keys.Control)
            {

                if (keyData.ToString() == "S, Control")
                {
                    // 新建记录,留下某个字段为空,这个字段必须有值的. 

                    //2. 然后Ctrl+S保存, 系统提示'xxx 字段必须有值', 这个时候,如果焦点在某个字段中, 那么这个时候会留下一个 's' 字符. 
                    //if (Save)
                    //{
                    //   // Fcdbas.WinUI.Common.cSessionManager.DbTransactionBegin();
                    //    SalWindow.FireWindowActions(this, Const.PM_DataSourceSave, 1, 0);
                    //}
                }
                else if (keyData.ToString() == "N, Control")
                {
                    if (CurrentSourceBinding.Updates == Platform.Enums.UpdatesSql.ReadOnly || !CurrentSourceBinding.AllowNew)
                    {
                        this.ShowMessage("不允许新增记录");

                    }
                    else
                    {
                        SalWindow.FireWindowActions(this, Const.PM_DataRecordNew, 1, this.CurrentSourceBinding.Identify);
                        SalWindow.FireWindowActions(this, Const.PM_DataSourceReBinding, 1, this.CurrentSourceBinding.Identify);
                        ((frmMainForm)this.MainForm).EnableSave = true;
                    }
                }
            }
            if (m_acceleratorTable != null && m_acceleratorTable.Count > 0)
            {
                foreach (KeyValuePair<Keys, cButton> btn in m_acceleratorTable)
                {
                    if (keyData == btn.Key)
                    {
                        btn.Value.PerformClick();
                    }
                }
            }
            return base.ProcessCmdKey(ref msg, keyData);
        }

        private void miCopyObject_Click(object sender, EventArgs e)
        {
            if (CurrentSourceBinding == null || CurrentSourceBinding.Current == null)
                return;
            Control ctrl = WinUtil.GetFocusedControl();
            if (ctrl != null && ctrl is cGridControl)
            {
                cGridControl grid = ctrl as cGridControl;
                List<IEntity> ens= grid.GetSelectEntityList<IEntity>();
                StringBuilder sb = null;
                foreach (IEntity en in ens)
                {
                    string attr = en.GetAttr(false);
                    if (sb == null)
                        sb = new StringBuilder(attr);
                    else
                        ClientSys.AddAttrToGroup(sb,attr);
                }
                sb.Append(ClientSys.logicalunit_separator_);
                sb.Append(CurrentSourceBinding.ObjectUnit);
                Clipboard.SetText(sb.ToString());
            }
            else
            {
                IEntity en = CurrentSourceBinding.Current as IEntity;
                if (en == null)
                {
                    this.ShowMessage("请选择要复制的记录", "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                string attr = en.GetAttr(false);
                if (string.IsNullOrEmpty(attr))
                    return;
                attr += ClientSys.logicalunit_separator_;
                attr += CurrentSourceBinding.ObjectUnit;
                Clipboard.SetText(attr);
            }
            //iNewRecord_ItemClick(this, e);
            //if (iSave.Enabled)
            //{
            //    if (currentForm == null || currentForm.CurrentSourceBinding == null || currentForm.CurrentSourceBinding.Current == null)
            //        return;
            //    en = currentForm.CurrentSourceBinding.Current as IEntity;
            //    if (en == null)
            //        return;
            //    attr = Clipboard.GetText();
            //    Paste(en, attr, currentForm.CurrentSourceBinding);
            //    currentForm.CurrentSourceBinding.ResetCurrentItem();
            //}
            miPasteObject.Enabled  = true;
        }

        private void miPasteObject_Click(object sender, EventArgs e)
        {
            if (CurrentSourceBinding.Updates == Platform.Enums.UpdatesSql.ReadOnly || !CurrentSourceBinding.AllowNew)
            {
                this.ShowMessage("不允许新增记录");
                return;
            }
            string groups = Clipboard.GetText();
            string[] text = groups.Split(ClientSys.logicalunit_separator_);
            if (text.Length < 2)
                return;
            if (text[1] != CurrentSourceBinding.ObjectUnit)
                return;
            string[] attrs = ClientSys.GetAttrFromGroup(text[0]);
            if (attrs == null || attrs.Length == 0)
                return;
            foreach (string attr in attrs)
            {
                SalWindow.FireWindowActions(this, Const.PM_DataRecordNew, 1, CurrentSourceBinding.Identify);
                SalWindow.FireWindowActions(this, Const.PM_DataSourceReBinding, 1, CurrentSourceBinding.Identify);

                IEntity en = CurrentSourceBinding.Current as IEntity;
                if (en == null)
                    return;

                WinUtil.Paste(en, attr, currentSourceBinding);
                CurrentSourceBinding.OnDataRecordDuplicate(2);
                CurrentSourceBinding.ResetCurrentItem();
            }
            MainForm.EnableSave = true;
        }
        public void ImportToGrid(cGridControl grid, string attrs,DataSourceBinding dsb)
        {
            string[] atrs = ClientSys.GetAttrFromGroup(attrs);
            if (attrs == null || attrs.Length == 0)
                return;
            int nCount = 0;
            foreach (string attr in atrs)
            {
                if(string.IsNullOrEmpty(attr))
                    continue ;
               // SalWindow.FireWindowActions(this, Const.PM_DataRecordNew, 1, CurrentSourceBinding.Identify);
                //SalWindow.FireWindowActions(this, Const.PM_DataSourceReBinding, 1, CurrentSourceBinding.Identify);
                IEntity en = HasRecord(attr, dsb);
                if (en == null)
                {
                    if (!dsb.AllowNew)
                        continue;
                    dsb.QuickAddNew();
                    en = dsb.Current as IEntity;
                }
                else
                    en.Status = RecordStatus.Edit;
                if (en == null)
                    return;

                WinUtil.Paste(en, attr, dsb);
                nCount++;
                if(SplashScreenManager.Default != null)
                    SplashScreenManager.Default.SendCommand(LoadStatus.ShowProgress, string.Format ("已经导入{0}条记录",nCount));
              //  CurrentSourceBinding.OnDataRecordDuplicate(2);
                //CurrentSourceBinding.ResetCurrentItem();
            }
            grid.DataSource = null;
            grid.DataSource = dsb;
           // SetControlReadOnly(this, currentSourceBinding);
            //SalWindow.FireWindowActions(this, Const.PM_DataSourceReBinding, 1, CurrentSourceBinding.Identify);
            //currentSourceBinding.ResetBindings(false);
            MainForm.EnableSave = true;
        }
        private IEntity HasRecord(string attr, DataSourceBinding dsb)
        {
            List<string> keys = new List<string>();
            if (dsb == null || dsb.Columns == null || dsb.Columns.Count == 0)
                return null;
            foreach (DataItem di in dsb.Columns)
            {
                if (di.Flags == DataItemFlags.Key )//|| di.Flags == DataItemFlags.ParentKey)
                    keys.Add(di.ColumnName);
            }
            IEntityList list = dsb.DataSource as IEntityList;
            if (list == null)
                return null;
            foreach (IEntity en in list)
            {
                bool IsEqual = false;
                foreach (string key in keys)
                {
                    if (en[key] != null && en[key].ToString() == ClientSys.GetItemValue(key, attr))
                        IsEqual = true;
                    else
                    {
                        IsEqual = false;
                        break;
                    }
                }
                if (IsEqual)
                    return en;
            }
            return null;
        }
        private void miAttribute_Click(object sender, EventArgs e)
        {
            dlgWindowAttribute dlg = new dlgWindowAttribute(this,this.WinProfile);
            if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                SaveWindowProfile();
                SetControlReadOnly(this, this.currentSourceBinding);
            }
        }
        private fnd_user_profile CreateTemplate()
        {
            fnd_user_profile f = new fnd_user_profile();
            f.pres_object = this.GetType().FullName;
            f.identity = AppEnvironment.Session.USER_ID;
            f.type_flag = "T";
            f.Status = Core.RecordStatus.New;
            f.data_source = CurrentSourceBinding.Name;
            return f;
   
        }
        private void miSaveTemplate_Click(object sender, EventArgs e)
        {
            if(currentSourceBinding == null || currentSourceBinding.Current == null)
                return;
            IEntity en = currentSourceBinding.Current as IEntity ;
            dlgSaveTemplate dlg = new dlgSaveTemplate();
            if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                fnd_user_profile f = CreateTemplate();
                f.description = dlg.Title;
                f.note_text = dlg.Note;
                f.info = en.GetAttr();
                en.EditAttr("");
                this.SaveUserTemplatefile(f);
                UTemplates.Add(f);
                AddUserTemplateMenu();
            }
        }

        private void BaseMenu_Opening(object sender, CancelEventArgs e)
        {
            if (FocusDataItem != null && FocusDataItem is cPictureEdit)
            {
                cPictureEdit pic = FocusDataItem as cPictureEdit;
                if (pic.Properties.ShowMenu)
                    e.Cancel = true;
            }

            AddUserTemplateMenu();
            SetCopyObjectEnable();
        }
        /// <summary>
        /// 设置粘贴菜单
        /// </summary>
        public void SetCopyObjectEnable()
        {
            string groups = Clipboard.GetText();
            string[] text = groups.Split(ClientSys.logicalunit_separator_);
            if (text.Length < 2)
            {
                miPasteObject.Enabled = false;
                SetMergeMenuEnable(miPasteObject.Name, false);
                return;
            }
            if (text[1] != CurrentSourceBinding.ObjectUnit)
            {
                miPasteObject.Enabled = false;
                SetMergeMenuEnable(miPasteObject.Name, false);
                return;
            }
            miPasteObject.Enabled = true;
            SetMergeMenuEnable(miPasteObject.Name, true);
        }
        private void miSearch_Click(object sender, EventArgs e)
        {
            if (MainForm != null)
                MainForm.iQuary_ItemClick(MainForm, null);
        }

        private void miReadData_Click(object sender, EventArgs e)
        {
            //if (Save)
            //{
            //    if (this.ShowMessage(this, "当前数据未保存，是否继续？", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == System.Windows.Forms.DialogResult.No)
            //        return;
            //}
            //if (IsDataSourceQuery())
            //{
            //    MasterdataSourceBinding.UserWhere = "";
            //    CurrentSourceBinding.UserWhere = "";
            //    SalWindow.FireWindowActions(this, Const.PM_DataSourceRefresh, 3, this.MasterdataSourceBinding.Identify);
            //    if (CurrentSourceBinding.LogicalParent == null && CurrentSourceBinding.IsLimit && CurrentSourceBinding.Session.RecordCount > currentForm.CurrentSourceBinding.RecordLimit)
            //    {
            //        dlgAskFetch dlgFetch = new dlgAskFetch(CurrentSourceBinding.Session.RecordCount, CurrentSourceBinding, this);
            //        if (dlgFetch.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
            //        {
            //            SalWindow.FireWindowActions(this, Const.PM_DataSourceRefresh, dlgFetch.FetchMode, CurrentSourceBinding.Identify);
            //        }
            //    }
            //    else
            //        SalWindow.FireWindowActions(this, Const.PM_DataSourceRefresh, 2, CurrentSourceBinding.Identify);
            //    if (CurrentSourceBinding.Count > 0)
            //        MainForm.SetToolbarEnable(true);
            //    else
            //        MainForm.SetToolbarEnable(false);
            //}

            //MainForm.EnableSave = false;
            if (MainForm != null)
                MainForm.iRefresh_ItemClick(MainForm, null);
        }

        private void miNew_Click(object sender, EventArgs e)
        {
            //if (CurrentSourceBinding.Updates == Platform.Enums.UpdatesSql.ReadOnly || !CurrentSourceBinding.AllowNew)
            //{
            //    this.ShowMessage("不允许新增记录");
            //    return;
            //}
            //Control ctrl = WinUtil.GetFocusedControl();
            //if(ctrl is cGridControl)
           
            //{
            //    GridView gview = ((cGridControl)ctrl).MainView as GridView;
            //    if (gview != null)
            //    {
            //        gview.ClearSelection();
            //    }
            //}
            //SalWindow.FireWindowActions(this, Const.PM_DataRecordNew, 1, this.CurrentSourceBinding.Identify);
            //if (this.CurrentSourceBinding.Count == 1)
            //    SetControlReadOnly(this, CurrentSourceBinding);
            //SalWindow.FireWindowActions(this, Const.PM_DataSourceReBinding, 1, this.CurrentSourceBinding.Identify);
            //MainForm.EnableSave = true;
            if (MainForm != null)
                MainForm.iNewRecord_ItemClick(MainForm, null);
        }

        private void miDelete_Click(object sender, EventArgs e)
        {
            if (MainForm != null)
                MainForm.iDelete_ItemClick(MainForm, null);
        }

        private void miCopy_Click(object sender, EventArgs e)
        {
            if (MainForm != null)
                MainForm.iCopy_ItemClick(MainForm, null);
        }

        private void BaseForm_Activated(object sender, EventArgs e)
        {
            //this.MainForm.CurrentForm = this;
        }

        private void BaseForm_MdiChildActivate(object sender, EventArgs e)
        {
            //this.MainForm.CurrentForm = this;
        }

    }
    /// <summary>
    /// BO Work Mode
    /// </summary>
    public enum WorkMode
    {
        /// <summary>
        /// 新增模式
        /// </summary>
        New,
        /// <summary>
        /// 编辑模式
        /// </summary>
        Edit,
        /// <summary>
        /// 只读模式
        /// </summary>
        Read
    }
}
